c - my_strcat 与 malloc 发生泄漏

标签 c memory-leaks

我正在尝试重新编码函数 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/

相关文章:

c - 是什么限制了这个简单的 OpenMP 程序的扩展?

C编程,为什么我的代码有溢出?

c++ - 将 uint8_t* 更改为 char*?

objective-c - 在不泄漏内存的情况下,在 Objective C 中初始化实例变量的正确方法是什么?

c# - JetBrains 点内存 : Unable to import the dump: 64-bit dumps of 32-bit processes are currently not supported

c - 如何在不使用内置函数的情况下反转句子中的单词

java - 提高 JNA 性能

c++ - Haxe/openfl 文本字段内存泄漏

c++ - 如何释放C++类中静态指针指向的内存

c - 在函数内部分配内存时发生内存泄漏