Reputation: 188
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;
}
Upvotes: 0
Views: 1245
Reputation: 126887
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.
Upvotes: 2