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?

5
  • 6
    You are returning the address of a local variable, which is a well-known mistake in C. Commented Jan 16, 2012 at 2:52
  • Your code has a dangling pointer. Commented Jan 16, 2012 at 2:53
  • possible duplicate of Can a local variable's memory be accessed outside its scope? Commented Jan 16, 2012 at 2: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. Commented Jan 16, 2012 at 2:53
  • 3
    The extension _t 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. Commented Jan 16, 2012 at 3:02

2 Answers 2

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.
Sign up to request clarification or add additional context in comments.

2 Comments

I worked with a programmer who used to do this all the time - his argument was that it worked 99% of the time - facepalm!
No, ap is holding the address of a local variable, a.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.