Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of Bus: error 10 in C

Tags:

c

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 ?

like image 715
summerc Avatar asked Jan 03 '12 18:01

summerc


People also ask

What is bus error in C programming?

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.

What causes a bus error?

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.

What causes SIGBUS?

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.


1 Answers

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> 
like image 136
Mysticial Avatar answered Sep 19 '22 09:09

Mysticial