开发者

Does a pointer in .h automatically get set to NULL?

开发者 https://www.devze.com 2022-12-20 15:47 出处:网络
If I declare a pointer to a struct in .h for example: my_struct_t *ptr; ... and then I check 开发者_运维技巧if(ptr==NULL) in the code, without actually setting ptr to NULL or allocating memory for

If I declare a pointer to a struct in .h for example:

my_struct_t *ptr;

... and then I check 开发者_运维技巧if(ptr==NULL) in the code, without actually setting ptr to NULL or allocating memory for it, can I do that check to see if its equal to NULL?

essentially what I'm asking is, by having ptr in the .h, does it get set to NULL automatically, or do I have to do that?

Thanks, Hristo

revisiont: this is done in C


From K&R2nd:

In the absense of explicit initializations, external and static variables are guaranteed to be initialized to zero.

So, yes.

That appears to be in section A8.7 of the 1990 standard. Don't know where to look in the 1999 standard.


It is not a proper declaration, you'd have to declare it like this:

 extern my_struct_t *ptr;

And somewhere in a .c source code file actually define it:

 my_struct_t *ptr;  

Which will make it zero initialized.


To answer your question, yes it will be set to NULL. The variable will have global scope, and variables with global lifetime gets initialized to NULL (for pointers).

However, you should not place a variable definition in a .h file. If you include that .h file in more than 1 .c file, you will have multiple definitions of that variable, which is undesirable.

You should place a declaration in the header file, e.g.

extern my_struct_t *ptr;

And then in just one of your .c files, place a definition:

my_struct_t *ptr;


Global variables are automatically initialized to zero. See the cases in my answer to another question.

Mind that defining variables in a header file is very bad practice - if multiple source files include that header, you'll have duplicate symbols and won't be able to link the program. Better declare that variable as extern in the header and define it only in one source file.


extern struct foo* pfoo; in a header file and struct foo* pfoo; in one of the .c files outside of any function will get you static storage for the pointer and thus automatic initialization to zero.

extern qualifier is key here. It tells the compiler not to allocate storage for the pointer in every translation unit.


Here's what K&R says:

External and static variables are initialized to zero by default. Automatic variables for which is no explicit initializer have undefined (i.e., garbage) values.

Automatic variables are the ones declared inside a function. Since you said .h file, yours is probably outside and therefore static.

Otherwise, I believe you could add " = NULL" to the declaration and so you don't have to remember to do it elsewhere.

I try not to create any allocations or code in a .h file.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号