views:

74

answers:

3

Hi All,
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.

+1  A: 

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.

Mark B
+1  A: 

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 :)

Nikolai N Fetissov
+6  A: 

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.

anon