简体   繁体   English

错误分段错误(核心已转储)

[英]Error Segmentation fault (core dumped)

I am doing some exercises for my university course on C and I have the following code which exits with error Segmentation fault (core dumped) after the user has input the choice (1 or 2). 我正在大学的C语言课程中做一些练习,并且我有以下代码,在用户输入选择(1或2)后,该错误退出并出现错误Segmentation Fault(core dumped)。 I don't know if it's an issue that I am using ubuntu 16.04 and I am compiling my source code files with make command. 我不知道这是我正在使用ubuntu 16.04还是使用make命令编译源代码文件的问题。 Oh and please don't recommend to use the built-in c function strcpy because this exercise is supposed to "teach us' how to make our own string copy. 哦,并且不建议您使用内置的c函数strcpy,因为本练习旨在“教我们”如何制作自己的字符串副本。

So what am I doing wrong? 那我在做什么错?

#include <stdio.h>
#define SIZE 1000

char mystrcpy(char *dest,char *src);

main(){

    char str1[SIZE];
    char str2[SIZE];
    char str3[SIZE];
    int choice;



    printf("Give first string: ");
    gets(str1);
    printf("Give second string: ");
    gets(str2);
    printf("Choose one of two strings (1 h 2): ");
    scanf("%d",&choice);

    if (choice==1)
        mystrcpy(str3,str1);
    else (choice==2)
        mystrcpy(str3,str2);

    printf("\nFirst string is %s\n",str1);
    printf("\Second string is %s\n",str2);
    printf("\nThrid string is %s\n",str3);

}


char mystrcpy(char *dest,char *src){
    int i;

    while(1)
    {

        dest[i] = src[i];
        if (src[i] == '\0')
            break;

        i++;
    }

    return dest;
}

i is never initialized. i从来没有初始化。 (need 30 characters....) (需要30个字符。...)

You are not initializing i , so it starts at an indeterminate value, hence the segfault. 您不是在初始化i ,所以它以不确定的值开始,因此存在段错误。

Notice that enabling the warnings would have shown this problem immediately in this simple case; 注意,在这种简单情况下,启用警告将立即显示此问题。 in more complicated scenarios using a debugger would have shown that the value of i at the moment of crash would have been completely nonsensical. 在更复杂的情况下,使用调试器将表明崩溃时i的值完全是荒谬的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM