3

Well I have seen declarations like

char strng[20]="";
strcpy(strng,"Some_String");

Here it is well understood that when I declare strng[20], i am reserving 20 memory locations(bytes) for this character array so I can copy any string to it which is almost 20 characters long.

Also, a declaration like

char *strng;
strng=(char*)malloc(sizeof(char)*n);

Which will create a character pointer(2 bytes), and then memory is allocated viamalloc and the base address of the allocated memory is assigned to strng. Here,n bytes will be allocated.

But, I have seen declarations like

char *srtng;
strng="Some_Very_Long_Text";

So, How is memory being allocated in this case? Here I am declaring a char pointer(2 bytes) then assigning a string to it. If the size of this string isn, then how and where is this string stored? my pointer only holds its base address. when is memory allocated and how? I am not even using malloc here.

BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
Anish Sharma
  • 495
  • 3
  • 15
  • The linked page's answers might be too technical because they mostly focus on segments and what the standards say. I suggest that you think about it this way: The character array is within "load-time" memory. You are just assigning a pointer to it. Load-time memory (however the compiler&OS are implementing it) already exists at the time your program starts (and is filled with the appropriate data). It may be implemented this way: you click on an executable file, the OS copies the exe (including the char-array) into RAM, it does further setup, then starts the program, ..., you assign a pointer. – Bernd Elkemann May 18 '16 at 07:39

0 Answers0