「Hello World」由編譯器靜態分配。它是該計劃的一部分,存在於某個可通過該計劃尋址的地方;把它解決12
charVoidPointer最初指向由malloc的分配給你一些的地方;把它解決98
charVoidPointer =「你好......」導致charVoidPointer指向程序中的數據;地址12.你失去了先前包含在charVoidPointer中的地址98的蹤跡。
,你不能釋放內存不會被分配的malloc。
爲了證明字面我的意思:
void* charVoidPointer = malloc(sizeof(char) * 256);
printf("the address of the memory allocated for us: %p\n", charVoidPointer);
charVoidPointer = "Hello World";
printf("no longer the address allocated for us; free will fail: %p\n",
charVoidPointer);
你的意思是:
strcpy(charVoidPointer, "Hello World");
編輯:尋址存儲器,用於其他類型的
的例子
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
// an array of 10 int
int *p = (int*)malloc(sizeof(int) * 10);
// setting element 0 using memcpy (works for everything)
int src = 2;
memcpy(p+0, &src, sizeof(int));
// setting element 1 using array subscripts. correctly adjusts for
// size of element BECAUSE p is an int*. We would have to consider
// the size of the underlying data if it were a void*.
p[1] = 3;
// again, the +1 math works because we've given the compiler
// information about the underlying type. void* wouldn't have
// the correct information and the p+1 wouldn't yield the result
// you expect.
printf("%d, %d\n", p[0], *(p+1));
free (p);
}
實驗;將類型從int更改爲long或double,或者一些複雜類型。
有一個簡單的規則:**只釋放你從malloc獲得的**。在你的例子中,「Hello World」不是從malloc中獲得的。 – cnicutar 2012-07-14 16:16:35
您正試圖釋放靜態內存,字符串「Hello World」。分配內存後,將指針移動到其他位置,導致內存泄漏。 – 2012-07-14 16:17:01
現在我們知道爲什麼'std :: string'工作得更好! :-) C庫充滿了你永遠不會在C++中使用的東西('strpbrk',任何人?)。除非*必須*,否則不要打擾那些人。 – 2012-07-14 16:24:01