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)] = '\0';
puts(dyn_s);
return 0;
}
Cheers!
sis an uninitialized pointer; you are writing to a random location in memory. This will invoke undefined behaviour.You need to allocate some memory for
s. Also, never usegets; there is no way to prevent it overflowing the memory you allocate. Usefgetsinstead.