-2

The function f allocates its result always to the same address, that makes the main() function always print out the same result, how do I make the function allocate the variable an another address and free them.

int *f(int a) {
    int b = 2 * a;
    return &b;
}

int main(void) {
    int *p4, *p8;

    p4 = f(4);
    p8 = f(8);

    printf("p4: %i / p8: %i\n", *p4, *p8);
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
Mattia
  • 179
  • 15

2 Answers2

4

The function f does not allocate anything, it returns the address of a local variable with automatic storage. Accessing data via this pointer invokes undefined behavior as soon as b goes out of scope, when f returns. The compiler should be able to detect such a silly bug.

To allocate memory, you should use malloc:

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

int *f(int a) {
    int *p = malloc(sizeof(*p));
    if (p != NULL)
        *p = 2 * a;
    return p;
}

int main(void) {
    int *p4 = f(4);
    int *p8 = f(8);

    if (p4 != NULL && p8 != NULL) {
        printf("p4: %i / p8: %i\n", *p4, *p8);
    }
    free(p4);
    free(p8);
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
0

You have to declare b as static ore better yet,declare b as parameter in f function. You could do something like this

static bool f(int a,int *b)
{
    if(NULL == b)
    {
        return false;
    }
    *b = a * 2;
    return true;
}

It is better to write functions that return nothing(void) or a boolean to let you know if everything went fine and use pointers to modify data and reduce the use of the stack. Most safety-critical standards adopt this rule.

  • Neither of these options address the OP's question: *how do I make the function allocate the variable an another address and free them.* – chqrlie Feb 29 '16 at 22:54
  • Agree detection of success or failure of allocation is a good thing. Yet my experience with "safety-critical standards" disallowed memory allocation altogether. – chux - Reinstate Monica Feb 29 '16 at 22:59
  • Since he only needs a variable,there's no reasono to use malloc() and consequently free(),so i posted a possible (simple) solution to his problem that does not require the use of the functions mentioned before.From MISRA/C: "Rule 20.4 (required): Dynamic heap memory allocation shall not be used." –  Feb 29 '16 at 23:08