Reputation: 781
I have the following code:
int i;
for(i=0;i<2;i++) {
...
printf("i = %d\n",i);
rtdb_pull(rtdb, buf, &ncenter);
printf("i = %d\n",i);
...
}
When I run it, it goes through just fine while i=0, but as soon as i=1, the rtdb_pull function seems to decrement the counter, so I end up stuck in a loop. How is this possible? I don't pass i to rtdb_pull, nor does rtdb_pull use a variable called i.
If I do this, everything works just fine:
int i;
for(i=0;i<2;i++) {
...
printf("i = %d\n",i);
int j = i;
rtdb_pull(rtdb, buf, &ncenter);
i = j;
printf("i = %d\n",i);
...
}
For the record, I am using gcc 4.7.3 on Ubuntu 13.04 and compiling with ANSI c. I do not get any related warnings from the compiler.
Upvotes: 0
Views: 128
Reputation: 22966
It's clear that rtdb_pull()
is causing this, because otherwise the compiler would be broken.
What's happening is that rtdb_pull()
is overwriting i
caused by a programming mistake in this function. Coincidently i
is overwritten with 0
. Depending on where things end up in memory, your malicious function could have been overwriting other variables, or none at all.
It appears that your erroneous code does not overwrite j
, and that's just another coincidence.
Where this happens, can only be anwered when you supply the code of rtdb_pull()
plus the code where rtdb
, buf
, and ncenter
are defined and allocated.
Changing the code, like dynamically allocating ncenter
as you wrote, may make this problem disappear. But it won't fix the root cause. So be very careful, it may bite again!
Upvotes: 1
Reputation: 13196
Since it appears that rtdb_pull(rtdb, buf, &ncenter)
writes its results into buf
, and possibly ncenter
, I'd want to see how those are allocated. If buf
is a local, for example, and has too few bytes allocated to it, the function might be overflowing the buffer, bumping into other variables on the stack, including i
. Let's see those declarations and relevant assignments.
Upvotes: 0
Reputation: 11916
If your rtdb_pull() is a function of unmanaged assembly body and it has forgotten push-pop backups then possibly your loop-counter(which is better in a register rather than memory) is being mangled by the assembly code of rtdb_.
If the assembly's register backup is automatically done, then the error is outside of assembly body(rtdb_pull() may be a simple C function? then error must be an undefined behavioral memory-access)
Upvotes: 0
Reputation: 3807
First of all you have posted a code snippet and so there might some other reason or consideration as to why this is happening!, but the parameter rtdb
looks suspiciously like the address of the function rtdb
?
rtdb_pull(rtdb, buf, &ncenter);
Is this true, if so, does rtdb
have access to i?
Upvotes: 0