简体   繁体   中英

C pointer address changes on null pointer initialization in function

Disclaimer: I am new to C arrived here from other languages. What I observe breaks my head I do not even have a starting point to explain the observed behavior.

Scenario: Play around with a self-written stack implementation to get a feeling for the language and to compare different approaches.

Compiler in use:

gcc (Ubuntu 5.4.0-6ubuntu1~16.04.12) 5.4.0 20160609

Minimized code example:

#include <stdio.h>

struct stack_entry
{
    struct stack_entry *next;
    int *item;
};

struct stack
{
    struct stack_entry *first;
};

void push_to_stack(struct stack *s_ptr, int *item)
{
    struct stack_entry new_entry = {.next = s_ptr->first, .item = item};
    s_ptr->first = &new_entry;
    printf("item_address@push_to_stack %p\n", s_ptr->first->item);
}

void pop_from_stack(struct stack *s_ptr)
{
    printf("item_address@pop_from_stack %p\n", s_ptr->first->item);
    int* result = NULL; 
}

int main()
{
    printf("\n--stack test--\n");
    struct stack s = {};
    struct stack *s_ptr = &s;
    int value = 42;

    push_to_stack(s_ptr, &value);
    printf("item_address@main: %p\n", s_ptr->first->item);
    pop_from_stack(s_ptr);

    return 0;
}

Unexpected output:

--stack test--
item_address@push_to_stack 0x7fffa759b67c
item_address@main: 0x7fffa759b67c
item_address@pop_from_stack 0x7fffa759b680

As one observes the item_address@pop_from_stack differs for some reason. I expect the output:

--stack test--
item_address@push_to_stack 0x7ffdc30ee19c
item_address@main: 0x7ffdc30ee19c
item_address@pop_from_stack 0x7ffdc30ee19c

To receive the expected output I need to remove the pointer declaration+initialization. In case I leave it in place the unexpected output occurs. So the following does the change:

// int* result = NULL;  

But why? This totally puzzles me.

This will trigger undefined behavior later on:

struct stack_entry new_entry = {.next = s_ptr->first, .item = item};
s_ptr->first = &new_entry;

because new_entry will die when push_to_stack() ends.

But why? This totally puzzles me.

When compiled without optimizations, that line is likely making the compiler allocate space for result in the pop_from_stack() frame. Such a thing will make the behavior of the program change due to the undefined behavior shown above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM