C语言 我什么时候应该在 C 中使用 free()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7396925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When should I use free() in C?
提问by Koffeeaddict4eva
The code works as it is supposed to, though it never frees the memory allocated by malloc().
该代码按预期工作,尽管它从未释放malloc().
I have tried to free memory in any place that I can, but no matter where I do it, it breaks the program. Specifically, I get a "double free or corruption error." This is more of a question as to what free()and malloc()actually do? All of the problems with free are in the main:
我试图在任何我可以释放的地方释放内存,但无论我在哪里做,它都会破坏程序。具体来说,我得到一个“双重释放或损坏错误”。这更多是关于什么free()和malloc()实际做什么的问题?free的所有问题主要在于:
int main(int argc, char *argv[]){
if(argc!=2){
exit(1);
}
printf("CSA WC version 1.0\n\n");
int length = strlen(argv[argc-1]);
char file_to_open[length];
strcpy(file_to_open, argv[argc-1]);
//printf("filename:%s\n",file_to_open);
//create counters for output
int count_number_of_lines = 0;
int count_number_of_words = 0;
int count_number_of_characters = 0;
//create int size of default array size
int current_array_size = pre_read(file_to_open);
//printf("number of lines: %i\n",current_array_size);
//create string array of default size
char *strings_array[current_array_size];
//create a pointer to catch incoming strings
char *incoming_string=NULL;
int done=0;
while(done==0){
incoming_string=get_line_from_file(file_to_open, count_number_of_lines);
if(incoming_string!=NULL){
incoming_string=csestrcpy2(incoming_string);
//printf("incoming line: %s\n",incoming_string);
strings_array[count_number_of_lines]=(char*)malloc(strlen(incoming_string+1));
strings_array[count_number_of_lines]=csestrcpy2(incoming_string);
//printf("added to array:%s\n",strings_array[count_number_of_lines]);
count_number_of_lines++;
count_number_of_characters=(count_number_of_characters+(strlen(incoming_string)-1));
}
else{
done=1;
}
}
//all data is stored in a properly sized array
//count all words in array
int count=0;
int word_count=0;
char *readline;
while(count<current_array_size){
readline = csestrcpy2(strings_array[count]);
printf("line being checked: %s", readline);
int i=0;
int j=1;
while( j< strlen(readline)+1 ){
if(strcmp(readline,"\n")!=0){
if( (readline[i] == ' ') && (readline[j] != ' ') ){
word_count++;
}
if( (readline[i] != ' ') && (readline[j] == '\n') ){
word_count++;
}
}
i++;
j++;
}
count++;
}
printf("current word count: %i", word_count);
return 0;
}
char* csestrcpy2(char* src){
int i = 0;
char *dest;
char t;
dest = (char*) malloc(MAX_LINE);
while( src[i] != 'int *my_int_pointer;
my_int_pointer = malloc(sizeof(int));
'){
dest[i] = src[i];
i++;
}
dest[i] = 'free(my_int_pointer);
';
//printf("length:%i\n",i);
free(dest);
return dest;
}
回答by Florian
In general you only have to free memory that has been reserved for you dynamically. That means if you have a statement like this:
通常,您只需释放动态为您保留的内存。这意味着如果你有这样的声明:
char* csestrcpy2(char* src){
int i = 0;
char *dest;
char t;
dest = (char*) malloc(MAX_LINE); /*<<- This allocates memory that has to be freed*/
while( src[i] != 'main{
int *i;
..
..
i=(int *)malloc(sizeof(int));
...//so something with i
..
free(i);
return 0;
}
'){
dest[i] = src[i];
i++;
}
dest[i] = ' i++;
j++;
/// free here
free(readline);
}
count++;
}
printf("current word count: %i", word_count);
//free here as well
for(int k = 0; k < count_number_of_lines; k++)
{
free(strings_array[count_number_of_lines]);
}
return 0;
}
';
//printf("length:%i\n",i);
free(dest); /* This frees the memory, but you return a pointer */
return dest; /* to this memory. this is invalid. */
}
than you need to free the memory that was allocated (reserved) by malloc. if you are unsure where to free it than just free it at the end of the program, by using free;
比您需要释放由 malloc 分配(保留)的内存。如果您不确定在哪里释放它,而不仅仅是在程序结束时释放它,请使用 free;
strings_array[count_number_of_lines]=(char*)malloc(strlen(incoming_string+1));
In your file it looks like there will be memory allocated whenever there is a new line in the file you read (in the while(done==0)loop). so everytime after the ifin the this loop you have to free the memory that was used by the variable.
在您的文件中,只要您读取的文件中有新行(在while(done==0)循环中),就会分配内存。所以每次在if这个循环之后,你必须释放变量使用的内存。
Furthermore you need to free the memory that was allocated by for the readline variable. But as it was pointed out before you may have a memory leak there.
此外,您需要释放为 readline 变量分配的内存。但是正如之前指出的那样,您可能会在那里发生内存泄漏。
Hope this helps.
希望这可以帮助。
edit: Okay - I was already wondering about the csestrcpyfunction. Lets have a look at this function:
编辑:好的 - 我已经在想这个csestrcpy功能了。我们来看看这个函数:
What you could however free is the src pointer in that function. but remember: the pointer cannot hold information after the underlying memory is freed! It just points to a place in memory where it should not write or read anymore.
但是,您可以释放的是该函数中的 src 指针。但请记住:释放底层内存后,指针无法保存信息!它只是指向内存中不应再写入或读取的位置。
Furthermore the function copys the string as long as there is no '\0'. What happens if there is no terminator? The function keeps on copying from some memory adresses where it should not!
此外,只要没有“\0”,该函数就会复制字符串。如果没有终结者会怎样?该函数不断从一些不应该复制的内存地址中复制!
you should not use that function ;)
你不应该使用那个功能;)
回答by Keith Thompson
There needs to be a call to free()for each successful call to malloc().
需要有一个呼叫free()每个成功调用malloc()。
That doesn't necessarilymean that you need to have equal numbers of malloc()and free()calls in your code; it means that for every malloc()call that's executed when your program runs, you should call free(), passing it the pointer value you got from malloc(). malloc()allocates memory; free()tells the system that you're done with the allocated memory.
这并不一定意味着您需要在代码中具有相同数量的malloc()和free()调用;这意味着对于malloc()在您的程序运行时执行的每个调用,您应该调用free(),并将您从 获得的指针值传递给它malloc()。 malloc()分配内存;free()告诉系统您已完成分配的内存。
(You can almost certainly get away with not free()ingallocated memory when your program terminates, since it will be reclaimed by the operating system, but just as a matter of style and good practice you should still match malloc()s with free()s.)
(free()ing当你的程序终止时,你几乎可以肯定不会分配内存,因为它会被操作系统回收,但作为一种风格和良好实践的问题,你仍然应该将malloc()s 与free()s匹配。)
I'm ignoring calloc()and realloc()calls.
我无视calloc()和realloc()电话。
回答by Dayal rai
Dynamic memory allocation (malloc) allocates a memory block of requested size, and returns a pointer to the start of this block.Since we have taken this block from memory so its a good practice to return this back to memory after completion of task.
动态内存分配 (malloc) 分配一个请求大小的内存块,并返回一个指向该块开头的指针。由于我们已经从内存中取出了这个块,所以在任务完成后将其返回到内存是一个很好的做法。
Now as answer of your question , To be always on safe side you can call free function before making return.
现在作为您问题的答案,为了始终处于安全状态,您可以在返回之前调用 free 函数。
##代码##回答by Ed S.
As a general rule, for every mallocthere should be a corresponding free. You cannot however freesomething twice (as you have noticed by now). I don't see any calls to freein your code, so it's impossible to say where your problem lies, but I noticed right away that you mallocsome memory and assign it to readlineinside of a loop, yet you don't call freeon readlineat the end of the loop, so you are leaking memory there.
作为一般规则,对于每一个都malloc应该有一个对应的free. 但是,您不能free两次(正如您现在已经注意到的那样)。我没有看到任何调用free你的代码,因此它是不可能的,说您的问题所在,但我立刻注意到你malloc一些内存并将其分配给readline一个循环内,但你不叫free上readline在年底循环,所以你在那里泄漏内存。
回答by Chris Eberle
Think of mallocand freeas "begin" and "end". ANY time you call malloc, do what you need to and once you're done, always call free. Make sure to only free it once, double-free is a runtime error.
将malloc和free视为“开始”和“结束”。任何时候你打电话malloc,做你需要做的事情,一旦你完成,总是打电话free。确保只释放一次,双释放是一个运行时错误。
If you somehow lose the value returned by malloc(yes, this is what's happening with your code), then you have a memory leak (and the gates of hell open up, yada yada).
如果您以某种方式丢失了返回的值malloc(是的,这就是您的代码发生的情况),那么您就会发生内存泄漏(地狱之门打开了,yada yada)。
To re-iterate: free whatever malloc returns (except null).
再次重申:释放 malloc 返回的任何内容(空值除外)。
回答by Jan S
This should work.
这应该有效。
In general - any memory allocated dynamically - using calloc/malloc/realloc needs to be freed using free() before the pointer goes out of scope.
通常 - 任何动态分配的内存 - 使用 calloc/malloc/realloc 需要在指针超出范围之前使用 free() 释放。
If you allocate memory using 'new' then you need to free it using 'delete'.
如果使用“new”分配内存,则需要使用“delete”释放它。
回答by alf
This line:
这一行:
##代码##is being overriden by the line next to it, so it can be removed.
正在被它旁边的行覆盖,因此可以将其删除。
You should also add free(readline)after count++in the last loop to free the memory created by malloc.
您还应该在最后一个循环中添加free(readline)aftercount++以释放 malloc 创建的内存。

