Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unhandled exception when dereferencing char pointer in Visual C++ 2008

I'm trying to do some classic C development in Visual C++ 2008 that will modify the characters of a string like so:

void ModifyString(char *input)
{
  // Change first character to 'a'
  *input = 'a';
}

I'm getting a unhandled exception when I try to change a character. It seems like I could do this in Visual Studio 6 or using gcc, but maybe I'm just forgetting something. Does Visual Studio somehow pass char* by value (managing memory). If so, how do I turn this off?


1 Answers

You're probably passing a string literal somewhere:

ModifyString("oops");  // ERROR!

C and C++ allow you to implicitly cast from string literals (which have type const char[]) to char*, but such usage is deprecated. String constants are allowed to be allocated in read-only memory (and they usually are), so if you attempt to modify them, you'll get an access violation (aka segmentation fault or bus error). If the compiler doesn't put string constants in read-only memory, the program will still work, but it is undefined behavior.

The correct way to do this is to copy the string into a writeable buffer:

// one way:
char mystring[] = "test";
ModifyString(mystring);  // ok

// another way:
char mystring[64];  // make sure this is big enough!!
strcpy(mystring, "test");
ModifyString(mystring);  // ok
like image 76
Adam Rosenfield Avatar answered Nov 25 '25 09:11

Adam Rosenfield