2015-07-19 65 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