分割故障 - Ç [英] Segmentation Fault - C
本文介绍了分割故障 - Ç的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么以下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.
这篇关于分割故障 - Ç的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文