2014-04-07 204 views
0
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main(){ 
    int * p = malloc(sizeof(int)); 
    *p = 10; 
    *p += 10; 
    printf("%d", *p); 
} 

它給了我正確的值,如果它是malloc分配,但總線錯誤,如果我只是把它聲明爲:爲什麼這需要malloc'd?

int main(){ 
     int * p; 
     *p = 10; 
     *p += 10; 
     printf("%d", *p); 
    } 
+5

要哪個地址是你的'INT * p;'指出,如果你不特別指向任何地方嗎? – nos

+0

你的第二個程序可能發生的*最糟糕的事情是'p'可能碰巧指向你可以讀寫的內存。在那種情況下,你冒險破壞一些重要的數據結構。行爲是未定義的。 –

+0

可能會掉線,但最後還是免費的內存 –

回答

4

未初始化指針就是這樣;初始化。你期望它指向哪裏?它的價值是不確定的,閱讀/寫作會導致不確定的行爲。

它不指動態分配的內存(malloc),但它確實有指有效內存。例如,這將是罰款:

int main(void) 
{ 
    int x; 
    int *p = &x; 
    *p = 10; 
    *p += 10; 
    printf("%d", *p); 
} 
+0

哦!謝謝,這很有道理。我只是不明白爲什麼它需要malloc'd。所以只要指針初始化(指向某個東西),它不會給出錯誤? – Programmer24

+2

@ Programmer24:只要指針指向有效內存,即允許讀取或寫入的內存,那麼讀取或寫入該內存(在其邊界內)是完全有效的。 –

0
#include<stdio.h> 
#include<stdlib.h> 
int main() 
{ 

int *ptr; 
//*ptr=123; Error here....Becuase it is like trying to store 
      //some thing into a variable without creating it first. 

ptr=malloc(sizeof(int)); // what malloc does is create a integer variable for you 
          // at runtime and returns its address to ptr, 
          // Which is same as if you assingned &some_variable 
          // to ptr if it had been already present in your program. 

return 0; 
}