2

I'm new to C so please correct any mistakes I have.

Here's some code that's sort of like the code I have

//typdef stuff for apple, *apple_t here
apple_t get() {
    apple a;
    a.num = 0;

    apple_t ap = &a;
    printf("set num to %d\n", ap->num);
    return ap;
}

// ap above is placed into read(ap)
void read(apple_t ap) {
    printf("num: %d\n", ap->num);
}

Why is it that for the "set" print ap->num == 0, but when I do the printf in read function I get some junk number like -1218550893? What's going on? Is the integer set being freed? What is C doing? And how do you fix this?

Derek
  • 11,980
  • 26
  • 103
  • 162
  • 6
    You are *returning the address of a local variable*, which is a well-known mistake in C. – Jon Jan 16 '12 at 02:52
  • Your code has a [dangling pointer](http://stackoverflow.com/questions/5278859/c-dangling-pointer-question). – Peter K. Jan 16 '12 at 02:53
  • possible duplicate of [Can a local variable's memory be accessed outside its scope?](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) – Jon Jan 16 '12 at 02:53
  • Because you're pointing at a automatic variable that has gone out of scope and gotten overwritten. Essentially every very new c programer does this at least once and it is *wrong*, **wrong**, ***wrong***! Many duplicates. Solution either allocate the structure in the calling routine and pass in a pointer, or allocate on the heap with a `alloc` family function. – dmckee --- ex-moderator kitten Jan 16 '12 at 02:53
  • 3
    The [extension `_t`](http://stackoverflow.com/questions/231760/what-does-a-type-followed-by-t-underscore-t-represent/231807#231807) is technically reserved to the system. It is also aconventional to have the structure type given a typedef and to then make the `apple_t` into a pointer. You would perhaps make the structure into `apple_t`, or (perhaps) `xyz_apple_t` where `xyz` is a prefix you use for your structures to distinguish them from system structures. – Jonathan Leffler Jan 16 '12 at 03:02

2 Answers2

9

You are returning the address of a local variable.

In this case the variable a is a local variable. It is lost after the function ends.

There are two options to fix this:

  1. Return it by value. Don't return its address.
  2. Allocate memory for it using malloc(). But you must be sure to free() it later.
Mysticial
  • 464,885
  • 45
  • 335
  • 332
0

You are returning a local variable, that is not available after the function has returned.

C supports returning structs, so no need for a pointers at all:

apple_t get() {
    apple_t a;
    a.num = 0;
    return a;
}

The following code will copy the result, not returning a local variable.

UnixShadow
  • 1,222
  • 8
  • 12