Search code examples
cmemory-management

the value of a pointer changes after the call to printf


The values of pointers of a struct change after each call to printf.

I have the following structs:

struct block_meta_data
{
    size_t size; 
    struct block_meta_data * next; 
    int isFree; 
}; 
typedef struct block_meta_data block_meta_data;

struct list
{
    block_meta_data* base; 
    block_meta_data* end; 
}; 
typedef struct list list;

I defined a global variable of type list called blocks_list:

list blocks_list = {NULL, NULL};

and the main function looks like :

int main(void)
{
    char a[] = "hello"; 
    printf("%s\n", a); 
    return 0;  
}

Now, using a debugger, I observe the values of both fields of the 'blocks_list' variable before the call to printf and they both have the value NULL:

After the call to printf, the values of both fields change to:

I tried printing the values of both end and base (without using a compiler) and the issue still remains:

list blocks_list = {NULL, NULL}; 
int main(void)
{
    char a[] = "hello"; 
    printf("%s\n", a); 
    printf("base = %p | end = %p\n", blocks_list.base, blocks_list.end); 
    return 0;  
} 
output : 
hello
base = 0x555eed65d000 | end = 0x555eed65d000

Can someone explain why this is happening?


Solution

  • Can someone explain why this is happening?

    There are a few possible explanations:

    • you are not telling us the whole story (provide MCVE) -- this is the most likely one
    • this is a debugging artifact -- your debugger is confused and shows something that isn't actually happening
    • the compiler detected that blocks_list is not actually used, and didn't allocate any storage for it (usually the compiler would also set location of blocks_list to 0, which would prevent debugger from displaying it).

    Since you appear to be using Linux, note that you can tell where the value is overwritten using GDB watch points:

    (gdb) watch -l blocks_list.base
    (gdb) continue
    
    # GDB will stop when blocks_list.base changes its value