Example C Pointers. What's bad about it?

In our lecture we had the following example:

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

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

This has been shown as a bad example, but is not explained further. Why is that bad?

+4
source share
3 answers

Here

int *foo(int x) {

x- local non-static variable. Performing

return &x;

you are returning the address of a local variable x. It exists as long as the function executes, and when the function completes, this address will be invalid for you. Using

*pt = 17;

You are looking for this address and writing 17to this invalid memory location. This causes Undefined Behavior . This is why this code is bad.

+4
source

, . , , *pt = 17; .

static.

int *foo() {
    static int x;
    return &x;
}
int* pt = foo();
*pt = 17; 
+5

foo x , . , , ( , ).

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

, pt Undefined Behavior. malloc:

int *foo() 
{
    int *x = malloc(sizeof(int));
    *x = 0;
    return x;
}

int* pt = foo();
*pt = 17;
free(pt);
+4

All Articles