Program only runs with clang compiler

Viewed 76

When I compile this program with the clang compiler and then run it, I get this output:

sum = 9
product = 6
sum - product = 6 - 6 = 0

and when I compile it with the gcc compiler and run it, the program terminates with a segmentation fault. Why is this?

Another question, why does *sum have the value 6 in this part of the code?:

printf("sum - product = %d - %d = %d\n",
                          *sum, *product, *sum - *product);

Also, why does *sum - *product produce the value 0?

Here is the program:

/***********************************************************************
* This program will add two numbers and then it will multiply two other
* numbers. Finally, it will subtract the second result from the first
* result.
***********************************************************************/

#include <stdio.h>

int *add(int a, int b) {
    int result = a + b;
    return &result;
}

int *multiply(int p, int q) {
    int result = p * q;
    return &result;
}

int main() {
    int *sum = add(4, 5);
    printf("sum = %d\n", *sum);
    int *product = multiply(2, 3);
    printf("product = %d\n", *product);
    printf("sum - product = %d - %d = %d\n",
                          *sum, *product, *sum - *product);
    return 0;
}

2 Answers

Compile using clang compiler:

# clang prg.c 
prg.c:5:13: warning: address of stack memory associated with local variable 'result' returned [-Wreturn-stack-address]
    return &result;
            ^~~~~~
prg.c:10:13: warning: address of stack memory associated with local variable 'result' returned [-Wreturn-stack-address]
    return &result;
            ^~~~~~

Compile using gcc compiler:

# gcc prg.c 
prg.c: In function 'add':
prg.c:5:12: warning: function returns address of local variable [-Wreturn-local-addr]
     return &result;
            ^~~~~~~
prg.c: In function 'multiply':
prg.c:10:12: warning: function returns address of local variable [-Wreturn-local-addr]
     return &result;
            ^~~~~~~

Warnings are there for some reason. Don't ignore them.

Variable result is a local(automatic) non-static variable and its lifetime is limited to its scope i.e. the block in which it has been declared. Any attempt to access it outside of its lifetime lead to undefined behaviour1).


1). An undefined behaviour includes it may execute incorrectly (either crashing or silently generating incorrect results), or it may fortuitously do exactly what the programmer intended.

You're returning pointers to local vars, which gives undefined behavior, as the local vars go away when the function returns, leaving the pointers dangling.

Try enabling warnings.

Related