简体   繁体   English

在C中释放重新分配的数组

[英]Freeing a Realloc'd Array in C

I am just starting to learn about malloc'd and realloc'd arrays. 我才刚刚开始学习有关malloc和realloc的数组。 Can anyone help explain to me how to properly free my following array? 谁能帮我解释一下如何正确释放以下数组? I have tried looking at other posts, but I have a hard time understanding memory allocation in C. 我曾尝试看过其他文章,但我很难理解C中的内存分配。

char ** result = NULL;
int numSpaces = 0;

char * p = strtok(command, " ");

/* split string and append tokens to 'result' */
while (p)
{
    result = realloc (result, sizeof (char*) * ++numSpaces);

    if (result == NULL)
        exit (-1); /* memory allocation failed */

    result[numSpaces-1] = p;

    p = strtok(NULL, " ");
}

Freeing realloc -ed memory is not different from freeing malloc -ed memory, in that all you need is to call free on the result at the end, when you no longer need the memory. 释放realloc -ed内存是不是从释放不同malloc -ed记忆,在你需要的是拨打freeresult在最后,当你不再需要记忆。

Your code, however, has a pattern that may lead to a memory leak: you are assigning realloc -ed block back to result without checking it for NULL . 您的代码,但是,有可能导致内存泄漏的模式:要分配realloc -ed阻止回result不检查它NULL If realloc fails, the previous value of the result becomes unrecoverable, because it has been overwritten by NULL . 如果realloc失败,则result的先前值将变得不可恢复,因为它已被NULL覆盖。

Here is how you could fix this issue: 这是解决此问题的方法:

char **temp = realloc(result, sizeof (char*) * ++numSpaces);

if (temp == NULL) {
    free(result); // Free the old memory block
    exit (-1); /* memory allocation failed */
}
result = temp;

At some point after you are done using result , you need to call free(result); 在使用result完成之后的某个时候,您需要调用free(result); .

This might look like: 可能看起来像:

char ** result = NULL;
int numSpaces = 0;

char * p = strtok(command, " ");

while (p) {
    result = realloc (result, sizeof (char*) * ++numSpaces);
    result[numSpaces-1] = p;
    p = strtok(NULL, " ");
}

for (i=0; i<numSpaces; ++i)
    printf("word %d: %s\n", i, result[i]);

free(result);

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

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