This line of code below is an example of a potential memory leak we have been going over in class.
I cannot follow the code logically to get the output.
When I go through it line by line I think that the output should be "Sucess!! val1 -> 10, val2 -> 10"
but the actual output when I run the code is "Abort System - ERROR!! val1 -> 10, val2 -> 108"
.
It appears that when foo2
gets called the second time it overwrites the first element in the array with a value of 100.
I guess what I am not understanding is how the int x
in foo1
is linked to the array int x[10]
in foo2
. Shouldn't these not be linked to each other since they are both locally declared?
#include <stdio.h>
#include <stdlib.h>
int* foo1(int a, int b)
{
int *ptr, x;
ptr = &x;
x = a * b;
return ptr;
}
int foo2(int a, int b)
{
int i, c, x[10];
for (i=0; i < 10; i++) x[i] = 100;
c = a + b;
return c;
}
int main(void)
{
int *ptr;
int i, val;
int val1, val2;
for (i = 1; i <= 2; i++)
{
if (i % 2) {
val = foo2(3, 5);
ptr = foo1(1, 2);
val1 = val + *ptr;
}
else {
ptr = foo1(1, 2);
val = foo2(3, 5);
val2 = val + *ptr;
}
}
if (val1 != val2) {
printf("Abort System - ERROR!!\n");
}
else {
printf("Sucess!!\n");
}
printf("val1 -> %i, val2 -> %i\n", val1, val2);
return 0;
}