首页 > 解决方案 > C - 使用 malloc、realloc 和 free。我的内存泄漏太多了,怎么了?

问题描述

所以,我的目标是定义一个结构,其中有 -

  1. 命令名称(例如 - “打印”)
  2. 命令参数计数器
  3. 包含参数的字符串数组。

您可以查看我的代码,但我真的很难理解我做错了什么 -

  1. 我使用 malloc 动态设置 my_struct.command 大小
  2. 我使用 malloc 动态设置 my_struct.arguments 数组大小
  3. 我使用 realloc 为我设置的每个参数动态增加 my_struct.arguments 大小
  4. 我使用 malloc 动态设置 my_struct.arguments[i] 大小
  5. 我最后调用 cleanup() 来释放任何动态分配的指针。

我不断收到很多内存泄漏。但我不明白为什么。

帮助和提示将不胜感激。

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

struct  {
    char *command;
    int arguments_count;
    char **arguments;
} my_struct;

void cleanup(void);

int main() {
    int i;

    my_struct.command = (char *)malloc(6*sizeof(char));

    my_struct.command = "print";
    my_struct.arguments_count = 1;
    my_struct.arguments = (char **)malloc(sizeof(char *));

    my_struct.arguments[0] = "hello";

    for(i = 1 ; i < 10; i++) {
        my_struct.arguments = (char **)realloc(my_struct.arguments, sizeof(char *)*(i+1));
        my_struct.arguments[i] = (char *)malloc(8*sizeof(char));
        my_struct.arguments[i] = "hello";
        my_struct.arguments_count++;
    }

    printf("Arguments count is: %d\n", my_struct.arguments_count);
    printf("The arguments are:\n");

    for(i = 0; i < 10; i++) {
        printf("%s\n", my_struct.arguments[i]);
    }

    cleanup();

    exit(0);
}

void cleanup(void) {
    int i;

    for(i = 0; i < 10; i++)
        free(my_struct.arguments[i]);

    free(my_struct.arguments);
    free(my_struct.command);
}

标签: cmemory-leaksmallocvalgrind

解决方案


strdup - strdup() 函数返回一个指向新字符串的指针,该字符串是字符串 s 的副本。新字符串的内存使用malloc获得,并且可以使用free释放。

my_struct.command = strdup("print");

my_struct.arguments_count = 1;
my_struct.arguments = (char**) malloc(sizeof(char*));
my_struct.arguments[0] = strdup("hello");

for (int i=1; i < 10; ++i) {
    // if the number of args is known, allocate before entering the loop
    my_struct.arguments = (char**) realloc(my_struct.arguments, sizeof(char*)*(i+1));
    my_struct.arguments[i] = strdup("hello");
    my_struct.arguments_count++;
}

// in your cleanup use the arguments_count var instead of the literal 10
for (int i=0; i < my_struct.arguments_count; ++i)

你的错误是:

// allocate a memory block of 6 bytes
// assign the address of that block to command
my_struct.command = malloc(6);

// then you assigned the address of the string 'print' to command
// therefore the previous allocated block is lost -> mem leak
my_struct.command = "print";

// strdup does the following
return memcpy(malloc(strlen(str) + 1), str, strlen(str) + 1);

推荐阅读