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?
The segmentation fault is because
tpoints 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.