c - Issues with an example of memory leak -


this question has answer here:

this line of code below example of potential memory leak have been going on in class.

i cannot follow code logically output.

when go through line line think output should "sucess!! val1 -> 10, val2 -> 10" actual output when run code "abort system - error!! val1 -> 10, val2 -> 108".

it appears when foo2 gets called second time overwrites first element in array value of 100.

i guess not understanding how int x in foo1 linked array int x[10] in foo2. shouldn't these not linked each other since both locally declared?

#include <stdio.h> #include <stdlib.h>   int* foo1(int a, int b) {    int *ptr, x;     ptr = &x;    x = * b;    return ptr; }  int foo2(int a, int b) {    int i, c, x[10];     (i=0; < 10; i++) x[i] = 100;     c = + b;    return c; }   int main(void) {    int *ptr;    int i, val;    int val1, val2;     (i = 1; <= 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;   } 

in function foo1

int* foo1(int a, int b) {    int *ptr, x;     ptr = &x;    x = * b;    return ptr; } 

you returning address of x variable's scope within function foo1. once function returns , dereference pointer x accessing unscoped variable.

this results in unpredictable behavior.


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -