paj7777
paj7777

Reputation: 311

Access violation writing location error when using strcat

I am having problems when using the strcat function in C++.

If I do :

MyClass::MyClass(char* myString){

char* AnotherString = myString;
strcat(AnotherString, "bob");

}

Then everything is fine. However, if I do:

MyClass::MyFunction(){

char* AnotherString = "fred";
strcat(AnotherString, "bob");

}

I get an unhandled exception in strcat.asm. Any ideas?

Regards

Upvotes: 0

Views: 5018

Answers (3)

Pedro d'Aquino
Pedro d'Aquino

Reputation: 5230

The answer you need...

is to use C++:

std::string anotherString = "fred";
anotherString += "bob";

The answer you probably want...

is what both Let_Me_Be and Moo-Juice said, combined.

This bit of code:

char* anotherString = "fred";

is extremely dangerous and should by all means be avoided. fred is stored in a read-only section of the memory and cannot be changed -- it is essentially the same as a const char* for all pratical purposes. Note that char anotherString[] = "fred"; is a whole different story, as it actually stores a copy of fred, which can be modified at will.

However, as Moo-Juice pointed out, strcat concatenates the second argument after the first one, which means the first string must have enough allocated room to hold both of them. So in your case, char anotherString[] = "fred"; would do you no good, as anotherString would only be 5 bytes long. You should then write:

char anotherString[8] = "fred"; // fred + bob + 1
strcat(anotherString, "bob");

Of course, in a real world scenario you probably don't know the string sizes in advance, so you'd use malloc to allocate an adequated buffer.

Upvotes: 10

Šimon Tóth
Šimon Tóth

Reputation: 36451

First, the compiler shouldn't allow you to compile this (without warnings):

char* str = "fred";

The correct code is:

const char* str = "fred";

String literals are constants, therefore you can't modify their contents.

Upvotes: 1

Moo-Juice
Moo-Juice

Reputation: 38820

The buffer pointed to by "dest" in strcat(dest, src) must be large enough to hold the resulting string. So:

char* anotherString = "fred"; // 5 bytes including zero-terminator

e.g, no room for "Bob".

But, you've posted this in C++ so why are you using strcat() anyway?

#include <string>

std::string another = "fred";
another.append("bob");

Upvotes: 7

Related Questions