0

I have written following C code:

#include <stdio.h>
#include <stdlib.h>

int *getPointer(int var);
void anotherFunction();

int main ( int argc , char * argv [])
{
  int *intPtr = getPointer(3); 
  printf("%d\n",*intPtr);
  anotherFunction();
  printf ("%d\n",*intPtr);
  getPointer(5);
  printf("%d\n", *intPtr);
  return EXIT_SUCCESS ;
}

// Which problem occurs here?
int *getPointer(int var) {
  int *ptr=&var;
  return ptr;
}
void anotherFunction(){
  // do nothing
  int a [ 5 ] = { 4 , 5 , 6 , 7 , 8 };
}

The Output is:

3
7
5

I do not understand why the value of intPtr changes in the second printf() call. I would appreciate your help! Thank you

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
clearner
  • 81
  • 3

2 Answers2

1

This function is totally pointless and wrong:

int *getPointer(int var) {
  int *ptr = &var;
  return ptr;
}

ptr points to the local variable var (yes function parameters are more or less the same as local variables). But as soon as the function returns, that variable doesn't exist anymore. So the pointer returned by getPointer points basically to junk.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
0

The pointer you are getting is a pointer to var local variable. And that variable is stored in the STACK (not in heap).

So, a couple of things:

  1. Relying on pointers to STACK variables after the function call ended is just WRONG. Don't do that. Never.
  2. The second printf is printing something in the stack that was overwritten when you called anotherFunction. This worked in this case, but this behavior is UNDEFINED (it could also lead to a SEGMENTATION FAULT).
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292