Who modified my local variable?
sasha at asksasha.com
Mon Jun 12 13:14:43 MDT 2006
>There's no need to do all kinds of bizarre malloc and free (new and
>delete) calls when normal C and C++ scoping rules would accomplish the
>same things and be safer. Unless copying is a huge concern, my rule of
>thumb is to always use static allocations (local, on the stack of
>course) whenever possible.
Stack space could be a concern in a number of cases. But, yes, if you do not
recurse, it is only a few bytes, and the stack is not restricted too much, stack
allocation is preferable. It is also much faster than malloc(), and you do not
have to free.
Now the comment on the code:
void FunctionA(unsigned char *pLen)
*pLen = 16;
printf("T2 %d\r\n", *pLen);
unsigned char ucLen = 0;
printf("T1 %d\r\n", ucLen);
printf("T3 %d\r\n", ucLen);
One problem I see is that your variable is a char (1-byte), but you are printing
it with %d which should be used for an int (usually 4-byte). With printf this
could be a problem. printf() is a variable argument number function. It takes
the first argument, parses it, and then decides how to interpret the rest of
them. Depending on the implementation of printf() and the compiler, you could
have some interesting results. Change your char to int, and see if that fixes it.
Another possibility is that your actual code has a stack-smashing bug.
AskSasha Linux Consulting
More information about the PLUG