bus error: 10. C code, malloc example

bus, c, memory-segmentation

Solution

Here `p` points to a string literal after your assignment, NOT to your allocated memory!

Then you try to write into that memory with `memcpy`.

Many C compilers allocate string literals in read-only memory, hence the bus error.

To fix your problem, you should copy the characters h, e, l, l, and o into the space you allocated for `p` in the first line of `main`, using `strncpy`. This keeps `p` pointing to the memory you allocated yourself; the later `memcpy` will be fine (provided you don't overflow your buffer of course).

Note that in general when you assign to a string variable directly you are making the variable point to a different memory address. In your code you have allocated space for a couple of strings but when you assign string literals to the variables, you are changing the location to which they point, causing a memory leak.

Problem

When I try compiling the following C code, i get a bus error. I'm guessing it has something to do with the way I have called memcpy, however I cant figure it out. Any help would be greatly appreciated! ``` #include<stdio.h> #include<stdlib.h> #include<string.h> int main() { char *p = (char*)malloc(sizeof(char)*11); // Assign some value to p p = "hello"; char *name = (char*)malloc(sizeof(char)*11); // Assign some value to name name = "Bye"; memcpy (p,name,sizeof(char)*10); // Problem begins here return 0; } ```

Original source

Related problems