[英]Why this program is giving seg fault?
This is my program : 这是我的程序:
#include<stdio.h>
int main()
{
int *n;
int var;
scanf("%d",n);
printf("%d",*n);
}
as scanf
stores the value at specified address I am giving the address .Then I am trying to print value at address but its giving segfault. 由于
scanf
将值存储在指定的地址中,我给了地址。然后我试图在地址上打印值,但给了它段错误。
您应该为这样的指针分配内存:
int* n = (int*)malloc(sizeof(int))
It's because a block of memory has not been allocated to contain the integer value referenced by the variable n
. 这是因为尚未分配一块内存来包含变量
n
引用的整数值。 You have only initialized a pointer to the memory block, not the memory block itself. 您只初始化了指向存储块的指针,而不是存储块本身的指针。
If you instead do the following, the code will work: 如果您改为执行以下操作,则代码将起作用:
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
printf("%d", n);
}
var n
是指针,并且您没有为其分配内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.