Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is the memory allocated when I create this array? (C)

Let's say I do something like:

char* test[] = {"foo","bar","car"};

What exactly is this equivalent to if I did it the long way? Is this automatically creating memory that I will need to free? I'm just sort of confused. Thanks.

like image 373
zProgrammer Avatar asked Sep 30 '13 05:09

zProgrammer


1 Answers

You are declaring an array of pointers. The pointers point to string literals.

The variable test follows the normal rule, if it's an automatic variable(scope inside some function), when out of the function, it gets out of scope, so you don't have to free the memory. If it's statically allocated(global or static variable), it has a life as long as the program, so you don't have to free the memory either.

The string literals that the pointers point have static storage, so you don't free them either.

like image 133
Yu Hao Avatar answered Oct 06 '22 09:10

Yu Hao