Given the following code:
#include "stdafx.h"
#include "string.h"
static char *myStaticArray[] = {"HelloOne", "Two", "Three"};
int _tmain(int argc, _TCHAR* argv[])
{
char * p = strstr(myStaticArray[0],"One");
char hello[10];
memset(hello,0,sizeof(hello));
strncpy(hello,"Hello",6);
strncpy(p,"Hello",3); // Access Violation
return 0;
}
I’m getting an access violation at precisely the point when it attempts to write to the address of myStaticArray[0].
Why is this a problem?
Background: I’m porting old C++ to C# as primarily a C# developer, so please excuse my ignorance! This piece of code apparently wasn’t an issue in the old build, so I’m confused…
ppoints to a part of the string literal “HelloOne”. You mustn’t try to modify string literals, that’s undefined behaviour.Often, string literals are stored in a read-only part of the memory, so trying to write to them causes a segmentation fault/access violation.