0

I'm new to C++. I was practicing returning pointer from function when I ran into this printf problem. Putting 2 printf back to back produced some weird results.

Two versions of an add function.

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

int add(int a, int b) {
    int c = a + b;
    return c;
}

int* add2(int* a, int* b) {
    int c = *a + *b;
    return &c;
}

In main, if I put two printf back to back, the first one returns the right value, while the second one returns random numbers.

int main() {

    int x = 2, y = 4;

    int z1 = add(x, y); // Pass by value function, return value
    int* z2 = add2(&x, &y); // Pass by reference function, return pointer
    
    // This causes the problem
    printf("%d\n", z1); // 6
    printf("%d\n%d\n", *z2); // some random large number

    return 0;
 }

However, if I put both in the same printf, everything's fine.

printf("%d\n%d\n", z1, *z2);

Two printf of z1 also works fine.

printf("%d\n", z1); // 6
printf("%d\n", z1); // 6

Is it something related to pointers and how printf works?

I'm using Visual Studio 2019 Community Version default settings.

  • 2
    `add2` is undefined behaviour. You return a pointer to a local variable – Raildex Aug 24 '21 at 06:11
  • 2
    [Read the compiler warning message](https://gcc.godbolt.org/z/hs19vaEaG): "returning address of local variable or temporary: c". – Raymond Chen Aug 24 '21 at 06:11
  • 1
    Returning address of local variable is a bad idea – kuro Aug 24 '21 at 06:11
  • `return &c;` -- BOOM – David C. Rankin Aug 24 '21 at 06:12
  • 1
    The add2 method returns a pointer to the local variable. z2 in your example references some part of stack. There is no guarantee that it points to something useful. That is why you get this large number. – Dima Aug 24 '21 at 06:13
  • 1
    Here's what I understand. The fact that putting both vars into one printf makes it works is merely luck because the program's memory has not been overwritten by something else. z2 only stores the address but complier treats that address as destroyed as soon as add2 finished executing. Is that right? – Quang Nguyen Aug 24 '21 at 06:17
  • 1
    "I'm new to C++" There is no C++ specific code visible but plain C code. Are you sure you are using C++ at all? Do you run the code through a C++ compiler or a C compiler. Also unless you don't use both languages it should be avoided to tag both very different languages to a single question. – Gerhardh Aug 24 '21 at 11:51

0 Answers0