Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

questions regarding passing pointers [duplicate]

Tags:

c

pointers

I'm new to C so I know what a pointer is but I'm not convenient with the topic yet.

#include "stdio.h"
#include "stdint.h"
int *value(void) {
    int i=3;
    return &i;
} 

void valueTwo(void) {
    int x=35;
}

main() {
    int *ip;
    ip=value();
    printf("*ip is %d\n", *ip);
    valueTwo();
    printf("*ip==%d\n",*ip);
}

The above code prints *ip is 3 *ip is 35

What I do not understand is why *ip has changed from 3 to 35. From what I understand, this means the value at the address &i has been changed from 3 to 35. However, I don't understand how 35 got into that address. Can anyone explain? Thanks!

like image 781
Alan H Avatar asked Nov 24 '25 15:11

Alan H


2 Answers

What you are seeing is undefined behavior.

int *value(void) {
    int i=3;
    return &i;
}

As soon as the function finishes, int i goes out of scope. The pointer thus is invalid. Everything happening after that is undefined.

like image 102
dornhege Avatar answered Nov 27 '25 04:11

dornhege


You are returning address of local variable i that causes undefined behavior according to C standards, the problem is scope and life of local variable is within the function vaule() once control returns access to that variable via address is invalid memory instruction.

edit: If you compile your code with -Wall then it will also give you warning:

$ gcc -Wall  -pedantic x.c
x.c: In function ‘value’:
x.c:5:5: warning: function returns address of local variable 
[enabled by default]

suppose your code name is x.c

You can rectify your code with dynamic memory allocation as follows:

int *value(void) {
    int* i = malloc(sizeof(*i));  // it is dynamically allocated memory 
    *i = 3; // assigned 3 at allocated memory 
    return i; // safely return its address 
} 

Now, *i in main is safe because life of dynamically allocated memory is till program executes.

like image 21
Grijesh Chauhan Avatar answered Nov 27 '25 04:11

Grijesh Chauhan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!