下面,我的代码是。
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 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:
温度超出范围:
temp = cond;
cond = malloc(sizeof(int) * (++cond_size));
i = -1;
while (++i < cond_size)
cond[i] = temp[i];
所以您应该通过cond_size-1限制循环。