我正在 ubuntu 14.04 LTS 上使用 gcc 编译器来编译以下 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)
请指出我哪里做错了。
谢谢
最佳答案
您正在声明和使用指针(指向内存),但没有为它们分配空间。
只是声明:
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;
}
关于c - C 程序中的段错误(核心转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31505349/