c - C 程序中的段错误(核心转储)

标签 c gcc ubuntu-14.04

我正在 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/

相关文章:

linux - 使用 libusb 而不是 hidraw 编译 hidapi

c - 如何在sublime text 3中编译运行C?

c - 如何在 ARM Cortex-M 上使用 GCC 定点类型扩展?

ubuntu - 在 Ubuntu 14.04.5 中使用 cabal 时,如何在 Haskell 中安装分析库?

c - 参数错误的不兼容类型

c - 如何获取C中对象中所有字符串的长度

r - 错误 : package or namespace load failed for ‘data.table’ in library. dynam(lib, package, package.lib): 找不到共享对象 ‘datatable.so’

c - 转换为 void 时的警告**

c - Makefile .o 文件规则问题

c - objdump 报告的符号偏移量不再与运行时偏移量匹配