Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 912
Selastin George Avatar asked Apr 20 '26 05:04

Selastin George


1 Answers

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
like image 121
artm Avatar answered Apr 22 '26 05:04

artm