【问题标题】:Crashing on strcpy, not sure why?在 strcpy 上崩溃,不知道为什么?
【发布时间】:2013-04-05 15:55:41
【问题描述】:
   if (strlen(shortest) > strlen(longest)) {
            char *temp;
            strcpy(longest, temp);
            strcpy(shortest, longest);
            strcpy(temp, shortest);
     } 
 }

strcpy(longest, temp) --> 导致我的程序崩溃。这是详细的崩溃报告(我已经包含了正确的头文件,所以不是那样的。编译器还警告我使用未初始化的临时变量...):

程序收到信号 SIGSEGV,分段错误。
__strcpy_ssse3 () 在 ../sysdeps/i386/i686/multiarch/strcpy-ssse3.S:85
85 ../sysdeps/i386/i686/multiarch/strcpy-ssse3.S:没有这样的文件或目录。

【问题讨论】:

    标签: c string pointers segmentation-fault


    【解决方案1】:
            char *temp;
            strcpy(longest, temp);
    

    strcpystrcpy(dst, src) 不是 strcpy(src, dst)。源是右边的参数,不是左边的参数。

    此外,当您将 char *temp 的值传递给 strcpy 时,它不会被初始化。您需要为temp 分配内存来保存您复制的字符串,例如使用malloc

    【讨论】:

    • @girlrockingguna 您还必须解决我回答的第二点。
    【解决方案2】:

    有 2 个错误。

    1) 你需要先为 char *temp 分配内存;

    例子:

    char *temp;
    temp = malloc(4); // Allocate 4 character space. 
                      // Ensure to include #include <stdlib.h>2)
    

    2) strcpy 签名是 strcpy(dest, src)。在你的代码中它是 strcpy(src, dest) whih 是错误的。

    正确的例子: strccpy(temp, longest);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多