开发者

Uninitialized Automatic variable forcing value to random value

This may look like a trivial problem. Sorry in that case, I am not able to find the actual way. I understand that automatic variable are un-initilaized. So a code snippet provided below is likely to dump in block开发者_运维知识库-2

char *p;  
if(NULL == p)  
{  
   //do something  block-1 statement
}  
else  
{  
  //do something else  block-2 statement
}  

Now, in most of the platform the default value of the automatic variable is either 0 or NULL especially SUSE Linux flavours.

Question

a. Is there any compiler flag or any other option which will force the setting up of local variable to a "junk" value if un-initialized?

PS : I know that static analyzer tool will be easily able to detect the problem. I just wanted to know if this can be done at run time also through some flags/option setting.

I am using SUSE 10/HP-UX and AIX platforms.


You don't need static analysis tools - just compile with the -Wall flag to get the comiler to warn you about the problem. and don't look for "band-aid" solutions - simply initialise the variable yourself.


What you see here is an artifact of how memory is usually allotted to processes on Unix.

Since the stack segment is not stored in the disk-file image of the executable the OS has to allocate new pages to the stack at program start. These come as zero-filled initially, same as the .bss. This initial zero-filling of the stack is historical. There was an attempt to "simplify" it to not do that. Too many programs broke, so the move was abandoned.

Run your program for a while, make multiple function calls, - you'll see "junk" on the stack eventually :)


First, why do you want to do this at runtime when you can most likely catch it quicker and easier with compiler warnings or static analyzers?

I'm not aware of a compiler flag to do what you want, but I'm pretty sure external tools such as valgrind and Purify can monitor for such things.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜