8

Below is an exceedingly simple example. It compiles fine using gcc on Mac OS X (Snow Leopard). At runtime it outputs Bus error: 10. What's happening here?

char* a = "abc";
a[0] = 'c';
Nate
  • 5,237
  • 7
  • 42
  • 52
  • 1
    that's a string literal, you can't modify it, as your pointer points to a location in the text section of the code which is read-only. Use `char a[] = "abc"` as a short hand for creating a character array filled with your string. – steabert Sep 20 '11 at 05:40

5 Answers5

10

Your code sets a to a pointer to "abc", which is literal data that can't be modified. The Bus error occurs when your code violates this restriction, and tries to modify the value.

try this instead:

char a[] = "abc";
a[0] = 'c';

That creates a char array (in your program's normal data space), and copies the contents of the string literal into your array. Now you should have no trouble making changes to it.

Lee
  • 13,462
  • 1
  • 32
  • 45
3

You are trying to modify a string constant. Use this instead:

char a[] = "abc";
a[0] = 'c';
Vaughn Cato
  • 63,448
  • 5
  • 82
  • 132
  • So using char* is equivalent to stating const char*, except the compiler doesn't warn you? Instead you get a pleasant runtime error. If so, I see the usefulness of adding the const keyword. – Nate Sep 20 '11 at 05:43
  • 1
    It will warn you if you compile with -Wwrite-strings, which is unfortunately not enabled by -Wall – Per Johansson Sep 20 '11 at 06:35
3

This

char* a = "abc";

relies on a dangerous implicit conversion from const char[] (the type of a string literal) to char*. (In C++ this conversion has been deprecated for more than a decade. I don't know about C, though.)

A string literal must not be altered.

sbi
  • 219,715
  • 46
  • 258
  • 445
1

char *a = "abc" is a constant string stored in the .data section of an ELF binary. You are not allowed to modify this memory and if you do you incur undefined behavior in some cases it will give no error but not modify the memory in your case you get a bus error because you are attempting to access memory that you normally cannot (for writing purposes).

NAND
  • 663
  • 8
  • 22
Jesus Ramos
  • 22,940
  • 10
  • 58
  • 88
  • Actually, `"abc"` is the constant string, `char *a` is the initialization of a (non-`const`) pointer with the address of the first character in that constant. – sbi Sep 20 '11 at 05:55
  • @sbi yeah that's what I meant, should probably have worded it differently – Jesus Ramos Sep 20 '11 at 06:05
1

char *str = "string"; In such a case it is treated as a read only literal. It is similar to writing const char *str = "string". Which is to say that the value pointed to by the pointer str is a constant. Trying to edit will result in BUS ERROR.

NAND
  • 663
  • 8
  • 22
Anoop Menon
  • 619
  • 1
  • 4
  • 12