2015-07-19 59 views
-1

我使用gcc編譯器在Ubuntu 14.04 LTS的後續的c程序編譯分割故障(核心轉儲)在C程序

#include<stdio.h> 
    void main() 
    { 
     int *a,*b; 
     *a=2; 
     *b=3; 
      printf("\n printing address.....\n address of a = %d \n address of b = %d \n",a,b); 
     printf("\n\n printing values ..... \n value of a = %d \n value of b = %d \n",*a,*b); 
     } 

,當我運行上面的程序比我在輸出得到以下

 output: Segmentation fault (core dumped) 

請建議我在哪裏做錯了。
謝謝

+1

'INT A,B; INT * A =&A,* B =&B;'' – BLUEPIXY

+1

空隙main'是錯誤的,順便說一句。 'main'返回'int'。 – melpomene

+1

**總是**用'gcc -Wall -Weror'編譯你的代碼。這會阻止你犯這樣愚蠢的錯誤。 –

回答

5

你聲明和使用指針(指向內存),沒有爲他們分配空間。

剛剛宣佈:

int *a; 

不給你的內存使用,這只是聲明可以引用內存中的變量。

指針一旦聲明就是未初始化的,並且會指向不屬於你的內存的某部分。使用那個記憶 - 在你的情況下,在那裏寫一個值 - 會導致未定義的行爲;當您觸摸該內存時,您會看到核心轉儲。

爲了獲得一定的空間使用,瞭解malloc

int *a = NULL; // good practive to initialize/reset pointers to NULL 

// malloc will give you space for 1 int, and a will point to that new space 
a = malloc(sizeof(int)); 

if (a != NULL) // malloc returns NULL in the event of a failure 
{ 
    // a is non-NULL so now we can use the memory pointed-to: 
    *a = 5; 

    // other code that uses a goes here: 
    ... 


    // and when you're finished with a give the memory back: 
    free(a); 
    a = NULL; 
} 
+0

請告訴我如何分配指針空間 –

+2

如果你問這個問題,這意味着你真的需要學習C(課程或書)或切換到另一種語言 – galinette

+1

上面的答案是完全正確的。或者他可以學習困難的方式:-)詢問問題和谷歌搜索和打錯誤。花費更長的時間,但它讓你在那裏,或讓你想讀更多。 – clearlight

0

在聲明指針

int* p; 

它是作爲聲明整數變量類似:

int v; 

v的內容未初始化 - 與相同- 它也未初始化,所以當你使用p*p您可能會在內存中的任何地方解引用地址,即使在只讀內存中。相反,您需要初始化變量。

int v = 0; 
int* p = &v; // p points to v in memory