且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么时候应该在C中使用free()?

更新时间:2023-02-16 22:32:27

通常,您只需要动态释放已为您保留的内存.这意味着如果您有这样的声明:

In general you only have to free memory that has been reserved for you dynamically. That means if you have a statement like this:

int *my_int_pointer;
my_int_pointer = malloc(sizeof(int));

您需要释放由malloc分配(保留)的内存. 如果您不确定要在哪里释放它,而不仅仅是在程序结束时通过使用free来释放它;

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;

free(my_int_pointer);

在您的文件中,只要您读取的文件中有新行(在while(done==0)循环中),似乎就会分配内存.因此,每次在此循环中的if之后,您都必须释放该变量使用的内存.

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 if in the this loop you have to free the memory that was used by the variable.

此外,您需要释放为readline变量分配的内存.但正如之前指出的那样,您可能在那里内存泄漏.

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.

希望这会有所帮助.

edit:好的-我已经想知道csestrcpy函数了.让我们看一下这个功能:

edit: Okay - I was already wondering about the csestrcpy function. Lets have a look at this function:

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] != '\0'){
        dest[i] = src[i];
        i++;
    }
    dest[i] = '\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.                */
}

您可以免费使用的是该函数中的src指针.但是请记住:释放基础内存后,指针将无法保存信息!它只是指向内存中不应再读写的位置.

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.

此外,只要没有'\ 0',该函数就会复制字符串.如果没有终结符,会发生什么?该功能会继续从某些不应该复制的内存地址进行复制!

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!

您不应使用该功能;)