附加到字符串时C中的内存泄漏

时间:2019-03-17 14:14:15

标签: c memory-leaks c-strings

Valgrind表示存在内存泄漏,但是我不知道这是什么。我尝试将free放到append函数中,将字符串释放到main的末尾,但仍然会抱怨。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void append(char* string, char c)
{
    int stringlength = strlen(string);
    char* tmp = realloc(string, sizeof(char) * (stringlength + sizeof(char) + sizeof(char)));
    if(tmp == NULL)
    {
        free(tmp);
        free(string);
        printf("Error appending character\n");
        exit(1);
    }

    string = tmp;
    string[stringlength] = c;
    string[stringlength+1] = '\0';
}

int main()
{
    char* string = malloc(sizeof(char));
    string[0] = '\0';

    printf("string before appending: %s\n", string);
    append(string, 'c');
    printf("string after appending: %s\n", string);
    free(string);
    return 0;
}

以下是Valgrind的输出:https://pastebin.com/dtXFm5YC (它位于Pastebin中,因此Stack Overflow实际上会让我发布此问题

1 个答案:

答案 0 :(得分:1)

您的主要问题不是内存泄漏而是无效访问:

Invalid read of size 1
    ...
Address 0x49d0028 is 0 bytes inside a block of size 1 free'd

和无效免费:

Invalid free() / delete / delete[] / realloc()
...
Address 0x49d0028 is 0 bytes inside a block of size 1 free'd

因为它们具有不确定的行为

  • 当您执行char* tmp = realloc(string, sizeof(char) * (stringlength + sizeof(char) + sizeof(char)));时释放了来自 main string ,因此,当您在中打印 printf 时, > main ,您可以访问已释放的块。请注意, realloc 释放块的事实不是强制性的

  • 因为您没有释放 realloc append 中由 realloc 新分配的 tmp ,所以会造成内存泄漏

  • 然后您再次释放 string 已被 realloc

  • 释放的字符串

还有sizeof(char) * (stringlength + sizeof(char) + sizeof(char))很奇怪,您所做的更改sizeof(char)根据定义1,可以只是stringlength + 2

您想要的:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void append(char ** string, char c)
{
   size_t stringlength = strlen(*string);

  *string = realloc(*string, stringlength + 2);

  if (*string == NULL)
  {
     fprintf(stderr, "cannot allocate memory\n");
     exit(1);
  }

  (*string)[stringlength] = c;
  (*string)[stringlength+1] = '\0';
}

int main()
{
    char* string = malloc(1);

    string[0] = '\0';

    printf("string before appending: '%s'\n", string);
    append(&string, 'c');
    printf("string after appending: '%s'\n", string);
    free(string);
    return 0;
}

编译和执行:

pi@raspberrypi:/tmp $ gcc -g -pedantic -Wextra m.c
pi@raspberrypi:/tmp $ valgrind ./a.out
==17097== Memcheck, a memory error detector
==17097== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==17097== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==17097== Command: ./a.out
==17097== 
string before appending: ''
string after appending: 'c'
==17097== 
==17097== HEAP SUMMARY:
==17097==     in use at exit: 0 bytes in 0 blocks
==17097==   total heap usage: 3 allocs, 3 frees, 1,027 bytes allocated
==17097== 
==17097== All heap blocks were freed -- no leaks are possible
==17097== 
==17097== For counts of detected and suppressed errors, rerun with: -v
==17097== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)