简体   繁体   English

内存泄漏,realloc()函数

[英]Memory leak, realloc() function

Here I want to extract words from 'text' string. 在这里,我想从'text'字符串中提取单词。 Dr. Memory says to me I have memory leak at line words = (char**) realloc(words, (amount + 1) * sizeof(char*)); 内存博士对我说,我在行words = (char**) realloc(words, (amount + 1) * sizeof(char*));出现内存泄漏words = (char**) realloc(words, (amount + 1) * sizeof(char*)); What is the problem? 问题是什么?

p = strtok(text, " ");
while(p != NULL) {
    words = (char**) realloc(words, (amount + 1) * sizeof(char*));
    words[amount] = strdup(p);
    amount ++;
    p = strtok(NULL, " ");
}
for(i = 0; i < amount; i ++) {
       free(words[i]);
}

Whn you use strdup it will allocate a new string. 当您使用strdup ,它将分配一个新字符串。 So before you release the array, you need to free each string you allocated with strdup . 因此,在释放数组之前,需要释放使用strdup分配的每个字符串。

You are not freeing the whole array though. 您没有释放整个数组。 The part you are allocating with realloc . 您使用realloc分配的部分。

So what is missing is a simple: 所以缺少的是一个简单的:

free(words);

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

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