Reputation: 586
Why this below code gives segmentation fault?
int main()
{
char *t = "Working on RedHat Linux";
char *s;
s = malloc (8000 * sizeof(char));
memcpy(s,t,7000);
printf("s = %s\nt = %s\n",s,t);
free(s);
}
I have allocated 8000bytes for 's'. And copying only 't' to s untill 7000bytes. Though I have allocated 8000 bytes for 's', why its giving segmentation fault?
Upvotes: 1
Views: 2940
Reputation: 13058
The segmentation fault is because t
points to a region smaller than 7000 bytes.
You are probably trying to read into an area when no readable page is mapped (after the end of string literal "Working on RedHat Linux"
).
You should limit your memcpy to sizeof("Working on RedHat Linux")
bytes.
Upvotes: 11
Reputation: 145899
Use:
memcpy(s, t, strlen(t) + 1);
to avoid memcpy
reading past the string literal array.
The C standard says regarding string functions (memcpy
is a string.h
function) (C99, 7.21.1p1).
"If an array is accessed beyond the end of an object, the behavior is undefined."
Upvotes: 2
Reputation: 1528
t points to a String buffer of length 24, but in memcpy you are trying to copy more than that (7000) which do not exist.
You are trying to access memory beyond what is allocated. So it is giving a segmentation fault
Upvotes: 1
Reputation: 213957
Your program exhibits undefined behavior: for memcpy() to work, both the source and the destination must be addressable for the number of bytes you've specified.
You've satisfied the destination, but not the source part.
Also, you can remove sizeof(char)
as it is defined by the standard to always be 1.
Upvotes: 4