Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Pointers Example - What is so bad about this? [duplicate]

Tags:

c

pointers

In our lecture we had the following example:

int *foo(int x) {
    return &x;
}

int* pt = foo(x);
*pt = 17;

It was shown as a bad example, but not further explained. Why is this bad?

like image 373
f1sh3r0 Avatar asked Dec 10 '22 23:12

f1sh3r0


2 Answers

Bad thing is that you are returning a pointer to an automatic local variable. It will no longer be exist once function returns and then the statement *pt = 17; will cause program to behave erratically.

A pointer to static local variable can be returned.

int *foo() {
    static int x;
    return &x;
}
int* pt = foo();
*pt = 17; 
like image 88
haccks Avatar answered Dec 13 '22 11:12

haccks


Here

int *foo(int x) {

x is a local, non-static variable. By doing

return &x;

you return the address of the local variable x. It exists as long as the function does , and when the function exits, this address will be invalid for you to play with. By using

*pt = 17;

you dereference this address and write 17 to this invalid memory location. This triggers Undefined Behavior. This is why the given code is bad.

like image 36
Spikatrix Avatar answered Dec 13 '22 13:12

Spikatrix