2

I know it is good to get in the habit of using the free() function to destroy a pointer when you're done with it, but what happens if a pointer is returned from a function? I assume it doesn't send a copy over, because there is no opportunity to destroy it. Does the pointer "switch" scope to the calling function?

Example (useless code, beware):

int* getOne(){
    int a = 1, *pA;
    pA = &a;
    return pA;  //what happens to this
}

int main(){
    printf("%i", getOne()); //uses data from the same addresses allocated to pA above?
    return 0;
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
galois
  • 825
  • 2
  • 11
  • 31
  • 1
    That's not a duplicate - a C++ reference and a C pointer are *not* the same thing. – Mark Bessey Jun 05 '15 at 07:50
  • @juanchopanza sir, this is similar in _concept_, but not a perfect dupe, IMHO. Can you please reconsider it? – Sourav Ghosh Jun 05 '15 at 07:55
  • @MarkBessey Maybe this one is better: http://stackoverflow.com/questions/2320551/return-pointer-to-data-declared-in-function?rq=1. There are so many of them duplicates, but I think the one used to close this covers it. – juanchopanza Jun 05 '15 at 08:02
  • Oh, I don't doubt that there are *lots* of duplicates - this is like the #1 problem for new C users. I just wasn't sure directing people to an answer for a different language would actually be helpful. – Mark Bessey Jun 05 '15 at 08:09

1 Answers1

3

No, your code invokes undefined behaviour, as the memory, which the pointer points to, no longer exists. If you want the returned pointer to be valid, you need to allocate memory to it dynamically, which lives beyond the function lifetime.

In C, you can use malloc() and family to allocated dynamic memory.

FWIW, free() doe not destroy a pointer. It deallocates the dynamically allocated memory to the pointer, if allocated. Calling free with a non-dynamically allocated pointer, will again result in UB.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261