Thursday, October 23, 2014

memory location of string literal in C

Answer:

The string literal will be allocated in data segment. The pointer to it, a, will be allocated on the stack.

#include <stdio.h>

int main()
{
char *a;

a = "tesaja";

return 0;
}
where will a allocated to ? stack or heap ?


 code will eventually be transformed by the compiler into something like this:
#include <stdio.h>

const static char literal_constant_34562[7] = {'t', 'e', 's', 'a', 'j', 'a', '\0'};

int main()
{
    char *a;

    a = &literal_constant_34562[0];

    return 0;
}
Therefore, the exact answer to your question is: neitherStackdatabss and heap are all different regions of memory. Const static initialized variables will be in data.

Reference:

No comments:

Post a Comment