-1

I know that many people asked this but I still have some questions about it. I read that writing:

char *string = "mystring";

Makes it a read only array of characters, if I were trying to do:

string[0] = 'l';

I would get an error. When I write:

char string[] = "mystring";

it is saved on the stack, just on the current scope. what about the char*? is it saved on the heap? or on the stack?

And when I tried writing:

char *string = "mystring";

And then:

string = "mystring2";

it worked, but what happened to the old "mystring" array? is there a memory leak caused by doing this?

Clifford
  • 88,407
  • 13
  • 85
  • 165
Danny
  • 125
  • 1
  • 7
  • https://stackoverflow.com/questions/9914007/string-literals-causing-small-memory-leak – J...S Jan 16 '19 at 11:25
  • "_I would get an error._" - strictly, you might, you might not; it is undefined. Any run-time error you get is down to OS or target platform behaviour rather than C run-time behaviour. Better to get a compile-time error by `const char *string = "mystring";`. – Clifford Jan 16 '19 at 12:33

1 Answers1

0

what about the char*? is it saved on the heap? or on the stack?

The char* is saved on the stack. But that's just one pointer. The actual string data will be stored in your program's executable (this happens when the program is compiled, it's not the char *string = "mystring"; that puts it there). The assignment to the char* initializes it with the address of "mystring" in your program's binary.

it worked, but what happened to the old "mystring" array? is there a memory leak caused by doing this?

Your executable will contain the content of both the "mystring"; and the "mystring2". When you do the string = "mystring2";, you make that pointer change from pointing to one to pointing to another. There's no memory leak here.

Blaze
  • 16,736
  • 2
  • 25
  • 44
  • I wanted to go into the specifics of OP's example, such as changing the pointer from one read-only memory location to another, what happens and why that works despite his observation of the "string" not being modifiable. – Blaze Jan 16 '19 at 11:30