2

When I'm trying to cast const char* to char* it crashes:

int myfunc(const char*);
const char * str = "test";
myfunc( (char*)str ) // crash

How can I do that?

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
deepspace
  • 771
  • 3
  • 11
  • 25

2 Answers2

4

What you're doing is undefined behavior.

You're not allowed to change the memory pointed to by str. If you need one you can change, declare it this way instead:

char str[] = "test";

This will create a mutable copy of the string literal "test" for you.

Collin
  • 11,977
  • 2
  • 46
  • 60
3

Update

Attempting to modify a string literal is undefined behavior. If we look at the draft C++ standard section 2.14.5 String literals paragraph 12 says:

Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation defined. The effect of attempting to modify a string literal is undefined.

Crashing is one of many possible results of undefined behavior it is also possible to have a program that appears to work properly.

Alternatively you can create a automatic array as follows:

char str[] = "test" ;

which will have a copy of the string literal which you can then modify.

Original

If myfunc is modifying a string literal then you have undefined behavior which can easily lead to your program crashing.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740