为什么此程序中的分段错误

时间:2012-11-22 06:50:30

标签: c

#include<stdio.h>

main()
{
int *A=NULL; 
*A=12; 
printf("The value of the ponter A is=%d",*A); 
}

此程序即将出现分段错误

2 个答案:

答案 0 :(得分:3)

取消NULL指针是undefined behaviour

    int *A=NULL; // creating a pointer to int and setting it to NULL
                 //means it points to nothing
    *A=12; // Now you try to dereference it so it's giving seg fault.

另一件事int *A不是NULL指针仍然直接为指针赋值是无效的意思,

int *A ;
*A=12; // It's invalid too

你应该试试这个:

int a=12;
int *A ;
A=&a; // assign later or you can so it in initialization

编辑:ISO c99标准:在给定段落的最后一行中予以考虑

6.5.3.2地址和间接运营商 约束

4    The unary * operator denotes indirection. If the operand points to a function,

 the result is a function designator; if it points to an object, the result is an lvalue 

    designating the object. If the operand has type ‘‘pointer to type’’, the result has 

type ‘‘type’’. If an invalid value has been assigned to the pointer, the behavior of the 

unary * operator is undefined.84)

答案 1 :(得分:2)

您需要为指针A指定内存位置。

以下陈述

int *A = NULL;

仅指出A是指向整数的指针,并且当前指向的地址为NULL。由于写入NULL和解除引用NULL是未定义的行为,因此您将遇到分段错误。

您需要使用malloc分配内存来解决问题或使指针指向有效对象。