-1

Without malloc() in sum_retbyptr(), the below program works well. Why it does not have error?
gcc -v 10.3.0 on Linux

#include <stdio.h>  
int *sum_retbyptr(int*, int*);  

int main(){  
    int a = 20, b=30, res;  
    res = *sum_retbyptr(&a, &b);  
    printf("Data transfer by return by ref : %d\n", res);  
    return 0;  
}  

int *sum_retbyptr(int* a, int* b){  
    int* ptr;  
    // ptr = malloc (sizeof(int));  
   *ptr = *a + *b;  
    return ptr;  
}
Bokyun Na
  • 79
  • 2
  • 5
    That's undefined behavior as `ptr` hasn't been initialized. Please turn on compiler warnings. – SuperStormer Sep 14 '21 at 06:51
  • 1
    *Why it does not have error?* **It does have an error**, the behaviour of the error is not what you seem to expect. – pmg Sep 14 '21 at 06:56
  • 1
    Compile with [`-g -fsanitize=address,undefined`](https://godbolt.org/z/vxjqznfKz) to get runtime help. – Ted Lyngmo Sep 14 '21 at 07:08

1 Answers1

2

Your program triggers undefined behavior, i.e.: a situation which is not defined by the C standard and in which everything may happen: program crashes, program gives invalid results, gasoline price goes up, and program could work perfectly as well (like in your case).

However, it is not reliable, since next time you start the program you may have a different behavior.

Interesting article about undefined behavior.


EDIT: the specific reason why your code triggers undefined behavior is because this line:

int* ptr;

... initializes ptr with a garbage address (just like int x; initializes x with a garbage int value). Therefore, the address contained in ptr is not guaranteed to be valid/usable, and it is not guaranteed to have enough space to contain an int value.

However, as you experimented, ptr's garbage address may work just fine. But it will usually crash your program in the long run.

Luca Polito
  • 2,387
  • 14
  • 20
  • You hit the core of the problem, maybe OP understands that the question is theoretically answered by this. But would you like to elaborate which detail of the program causes undefined behaviour? Note that the comments are not part of your answer. You could quote them (giving credit). – Yunnosch Sep 14 '21 at 07:42
  • @Yunnosch I've been more specific, thanks for the advice. – Luca Polito Sep 14 '21 at 07:58
  • Thank you for your answer. I have got you. – Bokyun Na Sep 15 '21 at 10:16
  • @BokyunNa You may mark my answer as accepted if it helped you. – Luca Polito Sep 15 '21 at 10:29