Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers To Const Char

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?

like image 346
2013Asker Avatar asked Aug 01 '13 20:08

2013Asker


People also ask

Can you make pointers to const?

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.

What is the difference between const char * p and char * const Q '?

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.

Can pointer change const value?

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.

How do the following operators differ 1 char const * p 2 char * const p?

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.


1 Answers

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

like image 102
Shafik Yaghmour Avatar answered Oct 21 '22 13:10

Shafik Yaghmour