本文介绍了分段错误 - C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下代码返回分段错误?当我注释掉第 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)] = '';
      puts(dyn_s);
      return 0;
    }

干杯!

推荐答案

s是一个未初始化的指针;您正在写入内存中的随机位置.这将调用未定义的行为.

s is an uninitialized pointer; you are writing to a random location in memory. This will invoke undefined behaviour.

您需要为 s 分配一些内存.另外,永远不要使用gets;没有办法防止它溢出您分配的内存.请改用 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.

这篇关于分段错误 - C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 16:35