Search code examples
cprintfdynamic-memory-allocationstdio

If a C function is called twice will it create a variable declared in the function twice?


I have a function written in C which consist of a pointer variable like this

#include<stdio.h>
void print()
{
    char *hello="hello world";
    fprintf(stdout,"%s",hello);
}

void main()
{
    print();
    print();
}

if i call the print() function twice, will it allocate the memory for the hello variable twice?


Solution

  • if i call the print() function twice, will it allocate the memory for the hello variable twice?

    No, it's a string literal and allocated just once.

    You can check that by checking the address:

    fprintf(stdout,"%p: %s\n", hello, hello);
    

    Sample output:

    0x563b972277c4: hello world
    0x563b972277c4: hello world