-1

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;  
}
jwpfox
  • 5,124
  • 11
  • 45
  • 42
ddej
  • 1
  • Aren't you returning the address of x in foo1?! – turbopapero Sep 13 '17 at 23:01
  • You are referencing an out-of-scope local variable, which could cause an exception and is generally bad practice. I don't see where memory would "leak". Perhaps this would be categorized as access-after-free. – hsmiths Sep 13 '17 at 23:02
  • There can be no memory leaks in a program without `malloc()` or a lower level allocation function like `sbrk()`. – Iharob Al Asimi Sep 13 '17 at 23:03
  • The issue is that you are returning a pointer to `x` in `foo1` but x has scope only within `foo1` – turbopapero Sep 13 '17 at 23:04
  • This is no *memory leak*. A memory leak occurs when you `malloc`, but then neglect to `free`. What you're doing is *accessing an object after it's been destroyed*, and is **very different**. May I suggest that you stop guessing and start reading? – autistic Sep 13 '17 at 23:13

1 Answers1

1

In your function foo1

int* foo1(int a, int b)
{
   int *ptr, x;

   ptr = &x;
   x = a * b;
   return ptr;
}

You are returning the address of x but this variable's scope is within the function foo1. Once this function returns and you dereference the pointer to x you are basically accessing an unscoped variable.

This results in an unpredictable behavior.

turbopapero
  • 932
  • 6
  • 17