[英]Memory allocation possible memory leak
What is the correct way to allocate memory for temp_comercial temp_active_substance ? 为temp_comercial temp_active_substance分配内存的正确方法是什么? could this allocation cause a memory leak? 这种分配会导致内存泄漏吗? I need just an answer to a correct form of allocate memory for the char pointers .. 我只需要为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);
This code alone can not decide if leak or not.. 仅此代码无法确定是否泄漏。
temp_comercial_name = malloc(order);
for(i = 0 ; i < order ; i++)
temp_comercial_name[i] = malloc( sizeof(char) * 20);
You have make sure you delete
/ free
memory in loop as below.. 您必须确保按如下所示循环delete
/ free
内存。
for (i=0; i<order; i++) {
free(temp_comercial_name[i] );
}
free(temp_comercial_name);
Edit: Setting NULL
after free
. 编辑:在free
之后设置NULL
。 There are quite a few discussion on this topic on SO. 关于SO的这个主题有很多讨论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.