-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Johs32 wrote:
I have the follwing code:
#include <stdio.h>
#include <stdlib.h>
struct data {
int *ip;
};
struct data first;
struct data *current = &first;
int init()
{
int a = 222;
current->ip = &a;
printf("init :%d\n", *current->ip);
return 0;
}
void zap(int a, int b)
{
printf("current->prio: %d\n",*current->ip);
}
int main()
{
init();
zap(3,5);
return 0;
}
When I do the printf in init() I get 222 as expected. But when I do it in
zap(int a, int b) I get 5!!
- From reviewing your code, I can see why.
[snip]
What kind of black magic is this?
There is no "black magic" involved. You just invoked "undefined
behaviour" by doing something incorrect in your code, that's all.
Tell me, at the printf() statement in init(), what does *current->ip
point to? What does it point to at the printf() statement in zap()? Is
there anything special about the object that *current->ip points to at
the point you get this odd behaviour?
Here's a hint: Unless you specify that the variable is "static",
variables defined within a function are only guaranteed to be available
/within/ the function that they were defined in, and they only last
until the end of the function. After that, any reference to them invokes
"undefined behaviour".
HTH
- --
Lew Pitcher, IT Specialist, Corporate Technology Solutions,
Enterprise Technology Solutions, TD Bank Financial Group
(Opinions expressed here are my own, not my employer's)
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2.2 (MingW32)
Comment: Using GnuPG with Mozilla -
http://enigmail.mozdev.org
iD4DBQFEFyZgagVFX4UWr64RArITAJ9wGtlihwpr7Bif8sOBF0 0/RvcfsQCYwWnd
b0lqTaSCbJvuiozW1KJnkw==
=5WY1
-----END PGP SIGNATURE-----