user2593573
user2593573

Reputation:

Appending character to end of char

I'm trying to append a space to the end of my char, this is the code I'm just testing with and it throws back a Bus Error;

int main() {
    char* test = "Test";
    printf("%s\n", test);
    strcat(test, "a");
    printf("%s\n", test);
    return 0;
}

Upvotes: 1

Views: 506

Answers (3)

Crowman
Crowman

Reputation: 25908

"Test" is a string literal, you're not allowed to modify it. If you change:

char * test = "Test";

to:

char test[10] = "Test";

it'll work as you expect it to.

EDIT: There's been some talk of whether this should have resulted in a compiler warning, in the comments. In C, char * test = "Test"; is perfectly well-formed and should not result in any warnings. On any sane implementation, strcat() will have been compiled a long time beforehand, so it can't give you any warnings, and since it expects a char * as its first argument, and that's what you pass it, that shouldn't result in warnings, either. It's possible that you could have a really smart compiler which both remembers that you pointed test to a string literal and haven't pointed it at anything else since, and knows that strcat() is going to change it, but this seems pretty unlikely, so I doubt you'd ever get any warnings here. It's one of those things you just have to know and avoid.

I believe the situation is different in C++. Compiling this with g++ -std=c++11 gives me a deprecated conversion from string constant to 'char *' warning, which you can eliminate by changing to const char * test = "Test"; This will then give you a new error when you try to pass a const char * to strcat(), which expects a plain char *. C++ type checking is more strict than with C.

Upvotes: 5

Some programmer dude
Some programmer dude

Reputation: 409166

The main problem here is that test points to a literal string, and literal strings are constant and therefore read-only. Attempting to change a literal string is undefined behavior.

If you want to append characters to a string, you have to allocate it first. Either on the heap (with e.g. malloc) on on the stack as an array. The allocated memory must also be big enough to be able to hold the extra character, in your case it has to be at least six characters: Four for the string "Test", one for the character 'a' and one for the special character that terminates all strings.

Upvotes: 3

Vallabh Patade
Vallabh Patade

Reputation: 5110

int main() {
    char* test = malloc(NUMBER_OF_BYTES);
    strcpy(test,"Test");
    printf("%s\n", test);
    strcat(test, "a");
    printf("%s\n", test);
    return 0;
 }

Upvotes: 0

Related Questions