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!
In practice, segfaults are almost always due to trying to read or write a non-existent array element, not properly defining a pointer before using it, or (in C programs) accidentally using a variable's value as an address (see the scanf example below).
Core Dump/Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you.” When a piece of code tries to do read and write operation in a read only location in memory or freed block of memory, it is known as core dump. It is an error indicating memory corruption.
See if your compiler or library can be set to check bounds on [i] , at least in debug mode. Segmentation faults can be caused by buffer overruns that write garbage over perfectly good pointers. Doing those things will considerably reduce the likelihood of segmentation faults and other memory problems.
Segmentation fault is an error caused by accessing invalid memory, e.g., accessing variable that has already been freed, writing to a read-only portion of memory, or accessing elements out of range of the array, etc.
s
is 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 use gets
; there is no way to prevent it overflowing the memory you allocate. Use fgets
instead.
Catastrophically bad:
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;
}
Better:
#include <stdio.h>
#define BUF_SIZE 80
int
main(int argc, char *argv[])
{
char s[BUF_SIZE];
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;
}
Best:
#include <stdio.h>
#define BUF_SIZE 80
int
main(int argc, char *argv[])
{
char s[BUF_SIZE];
int ln;
puts("Enter String");
fgets(s, BUF_SIZE, stdin); // Use fgets (our "cin"): NEVER "gets()"
int ln = strlen(s);
char *dyn_s = (char*) malloc (ln+1);
strcpy (dyn_s, s);
puts(dyn_s);
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With