Home > Back-end >  Which memory is being dereferenced by a struct pointer?
Which memory is being dereferenced by a struct pointer?

Time:06-13

So I'm trying to understand how pointers work, especially with structs.
Here's the code I'm trying to understand

struct Node {
    int val;
};

int main() {
    Node* a = (Node*) malloc (sizeof(Node));
    printf("%p\n", a);
    printf("%p\n", &(a->val));
    printf("%p\n", *a);
}

From my understanding if I print a, it would print the memory address of what was reserved by malloc. But I couldn't figure out which memory was being printed if I dereferenced a.

Here's the output.

00000000001C5D40
00000000001C5D40
00000000001C0150

I expected *a to be dereferencing the address of the first attribute. But as the output shows, it's not.
So which memory is being dereferenced?

CodePudding user response:

*a is the struct Node that a is pointing to. printf("%p\n", *a); passes the entire value of the struct Node. The “value” of a structure is an aggregate value composed of the values of all its members. In this case, there is just one member. And, since you did not assign any values to the member, its value is indeterminate.

However, for %p, you are intended to pass a pointer to printf (specifically a pointer of type void *). When you do not, the C standard does not define the behavior. The argument-passing mechanism may go awry in various ways. It might format the value in the member val as if it were a pointer and print that. Or it might print some unrelated data that happened to be a register where printf expected to find the pointer it should have been passed. Or your program could crash.

CodePudding user response:

When you dereference a pointer to struct Node (*a) you get the struct Node variable itself. If you had not initialized it you can get whatever (garbage). So in your case (00000000001C0150) is some garbage that was at the moment in variable struct Node. So I added one line in your code for clarity:

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int val;
};

int main() {
    struct Node* a = (struct Node*) malloc (sizeof(struct Node));
    a->val = 1;
    printf("%p\n", a);
    printf("%p\n", &(a->val));
    printf("%p\n", *a);
}

And I got the following result:

0xaaab04e522a0
0xaaab04e522a0
0x1

Hope, I help you a little bit)

  • Related