内存分配可能的内存泄漏

时间:2014-01-21 08:07:03

标签: c

为temp_comercial temp_active_substance分配内存的正确方法是什么? 这种分配会导致内存泄漏吗?我只需要对char指针的正确形式的分配内存进行回答..

int * temp_quantity;
void ** temp_pointers;
char ** temp_comercial_name;
char ** temp_active_substance;
char ** temp_manufacturer;
char ** temp_expiry_date;
int insertion_index, split, new_key, i, j;

new_leaf = make_leaf();

temp_keys = malloc( order * sizeof(int) );
if (temp_keys == NULL) {
    perror("Temporary keys array.");
    exit(EXIT_FAILURE);
}
temp_quantity = malloc( order * sizeof(int) );
if (temp_quantity == NULL) {
    perror("Temporary quantity array.");
    exit(EXIT_FAILURE);
}
temp_pointers = malloc( order * sizeof(void *) );
if (temp_pointers == NULL) {
    perror("Temporary pointers array.");
    exit(EXIT_FAILURE);
}

temp_comercial_name = malloc(order);
for(i = 0 ; i < order ; i++)
    temp_comercial_name[i] = malloc( sizeof(char) * 20); 

temp_active_substance = malloc(order);
for(i = 0 ; i < order ; i++)
    temp_active_substance[i] = malloc( sizeof(char) * 20); 

temp_manufacturer = malloc(order);
for(i = 0 ; i < order ; i++)
    temp_manufacturer[i] = malloc( sizeof(char) * 20); 

temp_expiry_date = malloc(order);
for(i = 0 ; i < order ; i++)
    temp_expiry_date[i] = malloc( sizeof(char) * 20); 

1 个答案:

答案 0 :(得分:4)

仅此代码无法决定是否泄漏..

temp_comercial_name = malloc(order);
for(i = 0 ; i < order ; i++)
    temp_comercial_name[i] = malloc( sizeof(char) * 20); 

您已确保循环中存在delete / free内存,如下所示。

for (i=0; i<order; i++) {
   free(temp_comercial_name[i] );
}
free(temp_comercial_name);

修改:在NULL之后设置free。在SO上有关于这个主题的讨论很多。

NULL after free or not