Question

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;
}
Was it helpful?

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.

OTHER TIPS

In your code, that p = "hello" the "hello" return a pointer which point to a string hello and the hello can't be change. You use p = "hello" means make p point to this string too. So when you try to change it, you will get an error. The right way is like follows: char a[] = "hello"; or

char *a = malloc(sizeof(char)*11); /*cast is not good*/
strcpy (a, "hello");

BTW, use malloc had better NOT using cast like (char *) or (int *).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top