Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where will the memory allocation for a string in C will take place

For the C statement given below i would like to know where the memmory allocation will take place.

char* ptr="Hello";//ptr is a automatic variable

then the pointer variable ptr will be allocated on the stack,but where will this string "Hello" be allocated. Is it on Stack or on Heap? And what about memory allocation for initialization statement like char ptr[]="Hello";

like image 881
prajul Avatar asked Nov 03 '11 19:11

prajul


People also ask

Where are strings stored in memory in C?

When strings are declared as character arrays, they are stored like other types of arrays in C. For example, if str[] is an auto variable then string is stored in stack segment, if it's a global or static variable then stored in data segment, etc.

Where is a string allocated?

The object str (it is the instance of the class std::string ) is allocated in the stack. However, the string data itself MAY BE allocated in the heap. It means the object has an internal pointer to a buffer that contains the actual string.

How does memory allocation occur in C?

In C, the library function malloc is used to allocate a block of memory on the heap. The program accesses this block of memory via a pointer that malloc returns. When the memory is no longer needed, the pointer is passed to free which deallocates the memory so that it can be used for other purposes.

How does the strings are stored in the memory?

Strings are stored on the heap area in a separate memory location known as String Constant pool. String constant pool: It is a separate block of memory where all the String variables are held. String str1 = "Hello"; directly, then JVM creates a String object with the given value in a String constant pool.


1 Answers

The standard doesn't say (it doesn't know about "stack", "heap" etc). But in practice the answer is: Neither. The string literal will be stored in the data section, usually in a read-only page.

As a side note, as Als mentions in the comments, it's undefined behavior to attempt to modify a string literal.

like image 170
cnicutar Avatar answered Nov 15 '22 05:11

cnicutar