2

When I declare a string like that:

char string[] = "Hello";

It is actually equivilant to -

char string[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

So a memory on the stack was allocated for the string by its declaration. But what happens when I declare a string like that:

char *string = "Hello";

The variable 'string' contains the address where the first letter of the string, 'H', is located on memory. I would like to ask:

  1. Where the string is located on memory? stack\heap\etc.

  2. Does enough memory is allocated for the string automatically, or I have to allocate memory (for example, by malloc) to the string by myself? And if I have to, how can I do that (I would like to a little example of code)?

I would like to note that there are good chances that the answer for my question is system-dependent. If it is, please note this fact, and try to answer according to what's happens on the popular platforms (Windows, Linux etc).

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Programmer
  • 750
  • 2
  • 9
  • 17
  • 1
    possible duplicate http://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s-in-c – tesseract Apr 09 '14 at 03:39
  • 1
    the important takeaway here is, when you do `char string[] = "hello"` you can do `string[0] = 'm'` to make it `mello` but if you did `char *string = "hello"` you can't do `string[0] ='m'` if the string is placed in read only memory by your compiler. – tesseract Apr 09 '14 at 03:50

1 Answers1

1

It isn't defined where the string in char *string = "Hello"; is stored. In practice, it is often in read-only memory called the text segment, where the code of the program is stored. The pointer is stored either on 'stack' or in the data segment, depending on whether the definition is inside a function or outside any function.

You don't have to do anything to allocate memory for the string.

The answer is not system dependent (except that a system may store the string in any convenient location and different systems might store it in different places).

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    Also, note that the memory used for constant strings is frequently (although not always!) set as read-only. Attempts to write to such a string will usually cause a segfault. To reflect this, pointers to such strings are properly typed as `const char *`; casting this to `char *` should be generating a warning! –  Apr 09 '14 at 03:47
  • @duskwuff Thanks, nice habit. – Programmer Apr 09 '14 at 03:54
  • I did mention that it is usually (often) in read-only memory. I didn't mention that the pointer should be defined as `const` too (as it should), nor that attempts to modify the string it points at will usually crash your program. – Jonathan Leffler Apr 09 '14 at 03:55