DEV Community

Discussion on: Why use pointers at all.

Collapse
 
jvarness profile image
Jake Varness

Hard-coded strings are considered to be of type const char* when compiled down, so the same rules that you would apply to anywhere that a char* is used. I can’t remember if const prevents you from reallocating the memory, or changing the address of the pointer. If I remember correctly, hard-coded strings are allocated in the heap, whereas other char* that are allocated at runtime are allocated on the stack.

I don’t think it creates a copy because pointers by their very nature are just memory addresses, but you can test this by examining the address as shown in this example: codingame.com/playgrounds/14589/ho...

Thread Thread
 
pentacular profile image
pentacular

Actually, they're not const char *.

A string literal produces a char array, so the type of "hello" is char[6], which evaluates to a value of type char *.

It is undefined behavior to mutate an object produced from a string literal, so it would be nice if the type system did help you out with a const, but backward compatibility ... :)

Note that there is no heap or stack in C. C has allocated, static, auto, and register storage instead.

Objects produced by modifying string literals can be allocated however the compiler likes, providing they have sufficient storage duration that nothing will ever notice them not being there anymore.

Because modifying them has undefined behavior they're often allocated in a read only part of the program's storage, like functions.

They may also be consolidated -- so you cannot expect "a" and "a" to produce distinct objects (but you also cannot rely on them not doing so).