我正在尝试重新编码函数 strcat,其中包含自动 malloc。 在一些测试中我可以看到我的函数中存在一些数据泄漏(我不知道正确的词)。
这是我的代码:
char *my_strcat(char *a, char *b)
{
char *result;
int i;
int j;
int la;
int lb;
la = -1;
lb = -1;
while (a[++la] != '\0');
while (b[++lb] != '\0');
result = malloc(sizeof(char) * (la + lb) + 1);
i = -1;
while (a[++i] != '\0')
result[i] = a[i];
j = -1;
while (b[++j] != '\0')
result[i + j] = b[j];
result[i + j] = '\0';
return (result);
}
因此,当我尝试在 while 循环中使用 my_strcat 和一些单长度字符串时,我得到一个:
a.out: malloc.c:2392: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.
Aborted (core dumped)
我正在尝试找出内存泄漏的根源。但我想不通。
这是调用部分:
while (!is_line_ended(read_result))
{
read(fd, read_result, READ_SIZE);
result = my_strcat(result, read_line(read_result, fd));
}
这是 MY_STRLEN:
# define MY_STRLEN(s) (sizeof(s)/sizeof(s[0]))
请注意,我仅限于一个文件和一个 header 。我被文件限制为 5 个函数,并且不允许使用字符串函数。
最佳答案
问题是你的宏#define MY_STRLEN(s) (sizeof(s)/sizeof(s[0]))
:
sizeof(s)
不返回 s
的字符串长度,而是返回 s
类型的大小,即 sizeof(char*)
.
使用strlen(s)
代替宏;如果出于任何原因不允许您使用 strlen,您可以使用以下函数:
int my_strlen(const char* s) {
int len=0;
while (*s++ != '\0')
len++;
return len;
}
关于c - my_strcat 与 malloc 发生泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41616085/