The following code points to the first character in a char array available in read-only memory. Is that right?:
const char * ptr = "String one";
Now when ptr
starts to point at another memory location:
ptr = "String two";
What happens to the first char array? Is that memory location freed when the execution ends?
A pointer to a const value (sometimes called a pointer to const for short) is a (non-const) pointer that points to a constant value. In the above example, ptr points to a const int . Because the data type being pointed to is const, the value being pointed to can't be changed. We can also make a pointer itself constant.
The difference is that const char * is a pointer to a const char , while char * const is a constant pointer to a char . The first, the value being pointed to can't be changed but the pointer can be.
const int * is a pointer to an integer constant. That means, the integer value that it is pointing at cannot be changed using that pointer.
NOTE: There is no difference between const char *p and char const *p as both are pointer to a const char and position of '*'(asterik) is also same. 2. char *const ptr : This is a constant pointer to non-constant character. You cannot change the pointer p, but can change the value pointed by ptr.
The standard only says that string literals have static storage duration, which means that the lifetime of the variable is until the program ends and it is initialized when the program starts. The relevant section in the C11 draft standard is 6.4.5
paragraph 6:
[...] The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. [...]
It could be in read only memory and probably is but that is implementation defined. It does not need to be freed, only memory that is dynamically allocated via malloc
needs a subsequent call to free
.
If I use this program:
int main()
{
const char * ptr = "String one";
return 0;
}
and we build it with gcc
and then use objdump
:
objdump -s -j .rodata a.out
We will find that in this case it is indeed stored in the read only data section:
Contents of section .rodata:
400580 01000200 53747269 6e67206f 6e6500 ....String one.
You can run it yourself here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With