3

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;
}
Shai
  • 111,146
  • 38
  • 238
  • 371
Sid
  • 1,239
  • 2
  • 13
  • 36
  • Other remarks: [Don't cast the return value of malloc](http://stackoverflow.com/questions/605845/). Why are you using `memcpy` for copying *strings* when `strncpy` and similar functions exist for that purpose? – DCoder Apr 21 '12 at 04:56

2 Answers2

10

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.

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
  • Is there any way to write on p ? – Sid Apr 21 '12 at 04:52
  • Thanks a lot! I've been trying to figure this out for a while now! – Sid Apr 21 '12 at 04:59
  • Shouldn't the code return a `seg fault` and not a `bus error`? Bus errors are memory access(es) the CPU cannot physically address while seg faults are memory access(es) the CPU cannot logically address (i.e. OP's problem). – lolololol ol Mar 30 '18 at 07:46
  • You get different errors with different compilers and different OSes for the same problem. For the OP's exact code, if you run it on JDoodle for C99, you get `Command terminated by signal 11`. On my Mac with clang (Apple LLVM version 9.0.0 (clang-900.0.39.2)) I get `Bus error: 10` – Ray Toal Mar 30 '18 at 23:29
0

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 *).

madper
  • 806
  • 1
  • 10
  • 25