0

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). 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. 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.

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;
}
Danae Vogiatzi
  • 178
  • 5
  • 23
  • 3
    Compile with all warnings & debug info (`gcc -Wall -Wextra -g`). Improve your code to get no warnings. Then **use the debugger** (`gdb`) – Basile Starynkevitch Feb 14 '17 at 20:09
  • 2
    ^^^ What Basile said. That will also give you a warning that `else (choice==2)` makes no sense whatsoever. (Though that's not the cause of the segfault.) – Mike Nakis Feb 14 '17 at 20:11
  • thank you! that was it! I was watching this as part of a tutorial. The guy never initialized i..still worked on him! Whatevs! Thanks again! – Danae Vogiatzi Feb 14 '17 at 20:16
  • Well that speaks for the quality of the tutorial... Steer away from it! – Matteo Italia Feb 14 '17 at 20:19

2 Answers2

4

i is never initialized. (need 30 characters....)

Roddy
  • 66,617
  • 42
  • 165
  • 277
2

You are not initializing i, so it starts at an indeterminate value, hence the segfault.

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.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299