Below is my code
#import <stdio.h> #import <string.h> int main(int argc, const char *argv[]) { char *str = "First string"; char *str2 = "Second string"; strcpy(str, str2); return 0; }
It compiles just fine without any warning or errors, but when I run the code I get the error below
Bus error: 10
What did I miss ?
In computing, a bus error is a fault raised by hardware, notifying an operating system (OS) that a process is trying to access memory that the CPU cannot physically address: an invalid address for the address bus, hence the name.
Bus errors can result from either a programming error or device corruption on your system. Some common causes of bus errors are: invalid file descriptors, unreasonable I/O requests, bad memory allocation, misaligned data structures, compiler bugs, and corrupt boot blocks.
You can get a SIGBUS from an unaligned access if you turn on the unaligned access trap, but normally that's off on an x86. You can also get it from accessing a memory mapped device if there's an error of some kind.
For one, you can't modify string literals. It's undefined behavior.
To fix that you can make str
a local array:
char str[] = "First string";
Now, you will have a second problem, is that str
isn't large enough to hold str2
. So you will need to increase the length of it. Otherwise, you will overrun str
- which is also undefined behavior.
To get around this second problem, you either need to make str
at least as long as str2
. Or allocate it dynamically:
char *str2 = "Second string"; char *str = malloc(strlen(str2) + 1); // Allocate memory // Maybe check for NULL. strcpy(str, str2); // Always remember to free it. free(str);
There are other more elegant ways to do this involving VLAs (in C99) and stack allocation, but I won't go into those as their use is somewhat questionable.
As @SangeethSaravanaraj pointed out in the comments, everyone missed the #import
. It should be #include
:
#include <stdio.h> #include <string.h>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With