分割故障 - Ç
问题描述:
为什么以下code返回段故障?当我注释掉线7条,赛格故障消失。
Why does the following code return with a segmentation fault? When I comment out line 7, the seg fault disappears.
int main(void){
char *s;
int ln;
puts("Enter String");
// scanf("%s", s);
gets(s);
ln = strlen(s); // remove this line to end seg fault
char *dyn_s = (char*) malloc (strlen(s)+1); //strlen(s) is used here as well but doesn't change outcome
dyn_s = s;
dyn_s[strlen(s)] = '\0';
puts(dyn_s);
return 0;
}
干杯!
答
取值
是一个未初始化的指针;您在内存中写入随机位置。这将调用的未定义行为
s
is an uninitialized pointer; you are writing to a random location in memory. This will invoke undefined behaviour.
您需要分配一些内存为取值
。此外,从来不使用获得
;有没有办法为prevent它溢出你分配的内存。使用与fgets
代替。
You need to allocate some memory for s
. Also, never use gets
; there is no way to prevent it overflowing the memory you allocate. Use fgets
instead.