1

I have this program in C

#include<stdio.h>

int main()
{
    printf("Hello New!\n");
    char c = 'd';
    char* s = "hello world";
    char **t = &s;
    *t[0] = c;
    return 0;
}

The program compiles but doesn't run. I have this output :

Hello New!
Bus error

I don't understand why

1
  • what are you trying to do? replace the first 'h' in "hello world" with 'd' so it reads "oello world"? Jan 11, 2011 at 22:28

4 Answers 4

3

String constants are stored in readonly memory and you cannot modify them.

If you must, then use:

#include<stdio.h>

int main()
{
    printf("Hello New!\n");
    char c = 'd';
    char s[] = "hello world";
    char **t = &s[0];
    *t[0] = c;
    return 0;
}

This allocates a local variable (not a constant) that is conveniently initialized and may be modified to your heart's content.

2

You may not modify the string that 's' points to, in any way. It is in a part of memory that you are not allowed to change.

2

String constants are unmodifiable, despite having the type char* rather than const char* for historical reasons. Try using the string constant to initialize an array, rather than a pointer:

#include <stdio.h>
int
main(void)
{
    char s[] = "hello new!";
    puts(s);
    s[0] = 'c';
    puts(s);
    return 0;
}
1

A bus error usually means that you're accessing a pointer with an invalid value - e.g. an address that is out of the address space.

I would guess that in this case, it is because you are trying to write to memory that is read-only. The string "hello world" is in a memory segment that you are not allowed to write to. Depending on the operating system, these memory segments are either protected or you can write arbitrary garbage to it. Seems like yours doesn't allow it. As you can see in the other answers, you can work around this by copying/initializing the string constant into an array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.