Tuesday, July 14, 2009

In C Function - before initializing a char variable, the char contains same junk - why?

With in a C program, I have a local C Function. In this function, I define a local char pointer. Before initializing the char, the char contains same junk value, even if I run millions of times - why?





How come the memory space contains the same junk char value - always?

In C Function - before initializing a char variable, the char contains same junk - why?
I'll give you the general answer. It'll be uninitialized because nothing initialized it to begin with. If it appears to be uninitialized every time you run, it could be the physical address is changing on each run. Now in your case, it sounds like you're looking at the same physical address each time, overwriting it, and re-running to see the data you overwrote. Either the overwrite failed, or between runs perhaps something else used the space. Your debugger can verify the overwrite if you dump the address space contents before leaving your program. As far as what uses that space after, there are software tools that let you watch writes to an address, but as you can imagine they're very intrusive and may end up changing the behavior you're seeing.
Reply:That's the way C language operates. Before initialization, your variable contains unexpected data.





This is a source of many bugs actually. Other programming languages might prohibit you from using unassigned variables (such as C Sharp)





Hope this helps.
Reply:Ok, as you know a local variable's value is stored on the stack--and you're asking why the uninitialized value of a local character variable doesn't return random data. The simple fact is that you are initializing values on the stack and then re-using them when you call the the function and examine the value of the local variable. As suggested in another answer, you can prove all this to yourself using a debugger. I like gdb that comes with gnu-c. Examine your stack and addresses that your local variables point to, etc. The debugger is an excellent way for you learn C and all of its nuances.


Good Luck


No comments:

Post a Comment