user3415993 user3415993 - 2 months ago 20
C Question

C: Variable value gets dirty while returning to calling function

Take a look at this code:

extern void f3(int);

void f2 (int foo) {
//some stuff
f3(foo)
printf("f2:%d\n",foo);
}
void f1 (int foo) {
//some stuff
f2(foo);
printf("f1:%d\n",foo);
}

int main() {
//some stuff
f1(foo)
//other stuff
return 0;
}


My problem is that i have outputs like:

f2: 1060 //this is the correct value
f1: 1065294485


There is no code between the print in the function f2 and the end of the function. There is no code between the call of the function f2 and the print in the function f1. How is possible this change of value?
I need to allocate big data structures in the stack and I'm using ulimit -s 2^28. I'm also using gcc -mO0 -m32 -msse to compile because the function f3 is written in nasm with sse. Can the problem depend on this?
Ask me for other things that may be helpful to understand the problem.

Edit: I'm showing the real f2() function:

void upgma_start(float* centroids,int k,int c,int d,float* size,float *md) {
float mc1 [d];
float mc2 [d];
upgma(centroids,k,c,d,size,md,mc1,mc2);
printf("uuu:::%d:\n",k);
}


the function upgma is the function f3 of the example code and k is the foo var.

Answer

I need to allocate big data structures in the stack

Why? Why can't you simply use malloc/free?

Can the problem depend on this?

Probably memory access in your f2 is out of bounds and reaches up into the stack frame of f1. This is not directly related to the size of your stack, but you likely have an out-of-bounds array access there, with an index too large instead of writing to the array in f2's stack frame you're trashing something in f1.

Had you used dynamic memory this problem would likely manifest itself as a segfault. I strongly suggest you switch to dynamic memory and use a memory debugger like Valgrind to track down the offending instruction in your code.