【发布时间】:2020-05-18 07:58:45
【问题描述】:
如下,我的代码是:
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 时是否存在内存入侵或其他错误?
【问题讨论】:
-
您的代码中有一些奇怪的东西:例如,为什么在存储分配的堆区域 malloc 的地址之后立即有
*cond = 0行?第一个 malloc 的内存将丢失。此外,您可能需要考虑检查 malloc 的 retun 值并使用 realloc 而不是自己做。
标签: c malloc heap-memory