如下,我的代码是:
int *text(char *str)
{
int *cond;
int *temp;
int cond_size;
int num;
int i;
cond_size = -1;
cond = malloc(sizeof(int) * 1);
*cond = 0;
while (*str != '\0')
{
if (*str == ' ')
str++;
num = 0;
while (*str >= '0' && *str <= '9')
num = num * 10 + *(str++) - '0';
temp = cond;
cond = malloc(sizeof(int) * (++cond_size));
i = -1;
while (++i < cond_size)
cond[i] = temp[i];
cond[i] = num;
free(temp);
}
g_size = (i + 1) / 4;
return (cond);
}
我的主要功能是:
int *text(char *str);
#include <stdio.h>
#include <stdlib.h>
int g_size = 0;
int main(void)
{
int *test;
int i;
i = 0;
test = text(" 4 3 2 1 1 2 2 2 4 3 2 1 1 2 2 2");
while(i < g_size)
{
printf("\n%d\n", test[i]);
i++;
}
}
使用输入字符串4 3 2 1 1 2 2 2 4 3 2 1 ...
,将输出以下输出:
==============
| 4 3 2 1 |
|4 '1'| <==
|3 2 |
|2 2 |
|1 2 |
| 1 2 2 2 |
==============
但是,当我检查(<==),
'1'被打印为'4',
而且这不符合我的预期。
使用malloc或其他错误时代码中是否存在任何内存入侵?
我可以看到一些问题:
cond_size为-1:
cond_size = -1; // Here is problem
cond = malloc(sizeof(int) * 1);
*cond = 0;
while (*str != '\0')
{
if (*str == ' ')
str++;
num = 0;
while (*str >= '0' && *str <= '9')
num = num * 10 + *(str++) - '0';
temp = cond;
cond = malloc(sizeof(int) * (++cond_size)); // you are trying allocate memory with size 0
i = -1;
while (++i < cond_size)
cond[i] = temp[i];
cond[i] = num; // you are writing to not allocated memory
您可以找到有关malloc的更多信息。
温度超出范围:
temp = cond;
cond = malloc(sizeof(int) * (++cond_size));
i = -1;
while (++i < cond_size)
cond[i] = temp[i]; // temp size is cond_size-1
所以您应该通过cond_size-1限制循环。
<script src="//onlinegdb.com/embed/js/SJADLQEM8?theme=dark"></script>