Why am I getting an access violation exception in a pointer operation?
I'm using C++ Visual Studio .Net 4.0 on Windows 7.0 x64. This happens just on the first loop of the while statement.
int main()
开发者_StackOverflow中文版{
char *string = new char[11];
string = "characters\0";
toUppercase(string);
return 0;
}
void toUppercase(char *stringPtr)
{
while(*stringPtr != '\0')
{
if(*stringPtr >= 'a' && *stringPtr <= 'z')
{
*stringPtr = *stringPtr - 32; // this is the culprit
}
++stringPtr;
}
}
I suspect you're doing something like this:
toUppercase("test");
The problem is "test"
is an array of const char
, not char
, so cannot be modified. However, due to a terribly stupid deprecated special conversion, a string literal can be treated as char*
anyway.
(Your function also fails to test for toUppercase(0)
.)
You can get #AV if memory isn't writeable:
toUppercase((char*)"str");
My guess would be that you are passing to that function a pointer to a string that resides in read-only memory. However, you would need to share the surrounding code -- i.e., how you actually call this method -- to pinpoint the problem.
EDIT: In view of the above, here's one way to get this working:
char* str = strdup("hello world");
toUppercase(str);
精彩评论