0

Possible Duplicate:
Modifying a C string: access violation

int main()
    {   
        char str_1[7] = "string";
        char* str_2 = new char[7];
        str_2 = "string";
        str_1[2] = 'a'; //ok
        str_2[2] = 'a'; //error

        return 0;
    }

i get "access violation" error here str_2[2] = 'a'; I don't understand why i can't access dynamic string via index here? (VS2010) Thanks.

Community
  • 1
  • 1
Alex Hoppus
  • 3,821
  • 4
  • 28
  • 47

4 Answers4

3

Instead str_2 = "string"; write strcpy(str_2, "string"), since in your case you are trying to modify string literal.

ForEveR
  • 55,233
  • 2
  • 119
  • 133
3

Allocates memory

char* str_2 = new char[7];

Disregards the previous allocation (and results in a memory leak), and makes str_2 point to a immutable string literal:

str_2 = "string";

str_2 will now actually point to a const char[], the implicit cast to char* is there just for backwards-compatibility. In fact it's pointing to read-only memory.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
3

You can not assign to a string like you do. Instead of copying the strings contents you copy the pointer. Thus str_2 now points to a string literal and can not be modified. To copy string's contents use strcpy.

Even worse- in your version of the code there is a memory leak for the memory allocated for str_2 in the line where you call new.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
1

The problem is that you do not do any "hard copy" of the memory cells anywhere, you just change pointers to point at different places. Strings are arrays and therefore have to be copied using the strcpy or memcpy functions.

char* str_2 = new char[7]; allocates dynamic memory. str_2 = "string"; lets the pointer str_2 point at a completely different memory cell, forgetting that it used to point at the allocated dynamic memory. Since there is no remaining reference to that memory, you know how a memory leak bug.

str_2 now points at a constant string literal "string" which resides in read-only memory. str_2[2] = 'a'; attempts to modify that memory, which is undefined behavior and you get a crash.

To understand why the str_1 case works, it is important to grasp the programming concepts intialization and assignment. The case of 'str_1' works because you allocate 7 bytes and then initialize those bytes to contain "string". At variable initialization is the only place where = will result in a hard copy from the read-only memory where the actual string literal "string" resides, to the stack in RAM where str_1 is allocated.

Lundin
  • 195,001
  • 40
  • 254
  • 396