简体   繁体   English

正确的释放记忆的方法

[英]Correct way to free memory

Makes a while since I've done some C and I have to refresh my understanding of pointers. 因为我已经做了一些C而且我必须刷新对指针的理解,这需要一段时间。 Here is a function that modifies the content of a pointer. 这是一个修改指针内容的函数。 The question is if this code is correct. 问题是这段代码是否正确。 Is it enough if I only free the pointer or do I have to free the content of by the pointer 如果我只释放指针或者我必须释放指针的内容就足够了

void foo(char **str) {
   // str has been allocated enough bytes for the following text
   *str = "allocate some text";
}

int main(int arc, char *argv[]) {
    char *someString;
    foo(&someString);
    free(someString); // is this the correct place to free
}

Thank you. 谢谢。

No, you don't want to call free() , because you never malloc() -ed the data. 不,你不想调用free() ,因为你从来没有malloc() ed数据。 More specifically, calling free() on a pointer to a string literal results in undefined behaviour . 更具体地说,在指向字符串文字的指针上调用free()导致未定义的行为

You shouldn't free at all in this case. 在这种情况下,你根本不应该自由。 free() should always correspond to a call to a malloc() function. free()应始终对应于对malloc()函数的调用。

Here you are 'freeing' constant memory that was never allocated in the first place. 在这里,你可以“释放”从未首先分配的常量内存。

There's something that puzzles me in this code. 在这段代码中有些东西让我感到困惑。

Why the comment says "str has been allocated enough bytes for the following text "? 为什么评论说“str已被分配足够的字节用于以下文本”? Even if it has been allocated, you are assigning to the pointer a new value, so it doesn't buy you anything having allocated that memory. 即使已经分配了,你也要为指针分配一个新值,所以它不会给你带来任何分配了那个内存的东西。

Anyway, according to this code, free() shouldn't be called. 无论如何,根据这段代码,不应该调用free()

You don't show in your code, but you write that str has been allocated with enough bytes. 你没有在你的代码中显示,但你写的str已经分配了足够的字节。 So that's fine, and can be free ed, but than you assign the pointer to the constant string to str - *str = "allocate some text"; 所以这很好,并且可以free编辑,但是将指针指向常量字符串为str - *str = "allocate some text"; (and as oli said, causes undefined behavior on free) instead perform strcpy() : (正如oli所说,在free上导致未定义的行为)而不是执行strcpy()

strcpy(str, "allocate some text");

First the call of the method foo should be adjusted, since the parameters don't match. 首先应该调整方法foo的调用,因为参数不匹配。 It should look something like 它应该看起来像

foo(&someString);

But personally I would agree to the place where you called the method free(someString) . 但就个人而言,我会同意你free(someString)调用方法的地方free(someString) Because the application is about to end and you no longer need any pointer. 因为应用程序即将结束,您不再需要任何指针。

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

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