0

Possible Duplicate:
Modifying C string constants?

can you explain why i get access violation on the mentioned line? i guess that is my process memory and i can access and change it's content.

#include <stdio.h>

int main()
{
    char* list[5]={"An","exam","on","Hall oween","night!!!!"};
    char **p;
    p=list;
    *(*(p+1)+2)='A'; //  <==== Access vioalation here
    return 0;
}
Community
  • 1
  • 1
Amir Zadeh
  • 3,481
  • 2
  • 26
  • 47

3 Answers3

5

Your code is equivalent to p[1][2]='A'; i.e. it wants to set the third char in the second string.

But since the strings are string literals they are immutable and you get undefined behavior when you try to modify their content. In particular they can be located in readonly memory. In which case you get an access violation.

Typically an executable file consists of different sections for code, global variables and constants. The executable gets mapped into the process and the memory access privileges get set to what's declared in the executable. Typically code is set to ReadExecute, global variables to ReadWrite and Constants to Read.
The CPU then enforces these memory access settings(Execute only on 64 bit CPUs). You can manually change the protection of memory using VirtualProtect. Note that it only has page granularity.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
  • If that is the case with string constants, then why isn't this true for const keyword? – Amir Zadeh Jan 15 '11 at 13:39
  • What do you mean by that? AFAIK most compilers put *compile-time* constants (and not variables you cast to const) into readonly memory. But they are free not to not make them readonly, since according to the standard writing to them is undefined behavior. – CodesInChaos Jan 15 '11 at 13:42
  • 1
    @Green Code - If you mean "why are string literals not `char []` instead of `const char []`," the reason is for backwards compatibility with existing C code when the standard was written. `const` wasn't universally implemented by compilers, so existing code had to use `char *c = "this";`. The standard decided that modifying string literals was a bad idea, but they didn't want code designed for pre-standards compilers to break, so they compromised. We've been suffering for it ever since. :P – Chris Lutz Jan 15 '11 at 13:50
  • @Chris I think you don't want the "not" before `char[]` – CodesInChaos Jan 15 '11 at 13:55
3

You're trying to modify string constants, which is undefined behavior. In this case the compiler is putting them in a read-only data segment.

Ferruccio
  • 98,941
  • 38
  • 226
  • 299
2

String literals in C are non-modifiable. You're declaring an array of pointers to string literals and then trying to modify them through it.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711