简体   繁体   English

Free()一个部分释放的字符串数组C.

[英]Free() a partially freed array of strings C

Assume that I have an array of strings, some of which are already free'd, as an example: 假设我有一个字符串数组,其中一些已经免费,作为一个例子:

char **array;
array = malloc(20*sizeof(char*));

for(i=0;i<arr_size;i++)
{
    array[i]='\0';
    free(array[i]);
}
free(array);

Is this a correct way to do it? 这是一个正确的方法吗? Because I still seem to get some memory leaks, in my case an array of 20 strings where 9 are already freed. 因为我似乎仍然有一些内存泄漏,在我的例子中是一个包含20个字符串的数组,其中9个已经被释放。

I guess the question is how to go about freeing "freed" strings. 我想问题是如何释放“释放”字符串。 Thanks for the help! 谢谢您的帮助!

I guess the question is how to go about freeing "freed" strings. 我想问题是如何释放“释放”字符串。

Well, you don't. 好吧,你没有。 You must free every malloc 'ed string exactly once. 您必须完全free每个malloc的ed字符串一次。 Calling free several times on the same string will lead to undefined behaviour. 呼叫free在同一个字符串几次会导致不确定的行为。

That aside, your problem is the following: 除此之外,您的问题如下:

array[i]='\0';

Here, you are overwriting the value of the pointer before you free it. 在这里,您在free之前覆盖指针的值。

By convention, you should always set a pointer to NULL after free -ing. 按照惯例,在free后应始终将指针设置为NULL Then you should check to see if the pointer is NULL , if not, then you can free . 然后你应该检查指针是否为NULL ,如果没有,那么你可以free That way you can keep track of which ones have been free -ed and which ones haven't. 这样你就可以跟踪哪些是free ,哪些没有。

1 malloc() allocation requires just 1 free() to deallocate memory. 1 malloc()分配只需要1 free()来释放内存。 So free(array); 所以free(array); is sufficient to deallocate the memory. 足以释放内存。

free() deallocating memory is counter to allocated memory dynamically using malloc() . free()释放内存与使用malloc()动态分配的内存相反。

Using free(array[i]); 使用free(array [i]); will cause problems / strange errors as you are trying to free a pointer whose value (pointer) you have changed on the previous line. 当您尝试释放其值(指针)在前一行上已更改的指针时,将导致出现问题/奇怪错误。

The code array[i]='\\0'; 代码数组[i] ='\\ 0';

may not have the desired results as it is setting the pointer value not the character contents. 可能没有所需的结果,因为它设置指针值而不是字符内容。 Perhaps sprintf(array[i],"\\0"); 也许是sprintf(array [i],“\\ 0”); would be better 会更好

char **array=NULL;  //(Helps you to give it an initial value pointing to NULL)

array = malloc(arr_size+1);  

if (!array[i])
{
// array == NULL which is not right after malloc
// there has been an error with malloc, trap and exit somehow
}
else
{
// Use array as you wish as it has been allocated, take care not to 
// run past the end of the array length
}

if (array[i]) free(array[i]);   // checks that it is not NULL anymore, as NULL does not need freeing.

You could expand the IF statement to: (means that same as above, but includes forcing a freed variable to NULL) 您可以将IF语句扩展为:(表示与上面相同,但包括强制释放的变量为NULL)

if (array[i]!=NULL) 
{
 free(array[i]);   
 array[i] = NULL;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM