bytes were returned when we access the structure m

2019-09-05 14:47发布

问题:

This question already has an answer here:

  • Crash or “segmentation fault” when data is copied/scanned/read to an uninitialized pointer 5 answers

I created one struct and assigned one pointer variable to that structure. When I tried to print the address of that variable it prints correctly. After assign value to one of the member of the structure using this pointer structure variable, when i tried to print the address of the pointer variable I got segmentation fault.

#include <stdio.h>

typedef struct node {
char mem;
double mem2;
char mem3;
int mem4;
char mem5;
char mem6;
}NODE;
int main()
{
    NODE * m;
    printf("%u",&m);

    return 0;
}

I got output as 3014616488. When I assigned variable to one of the structure member,

#include <stdio.h>

typedef struct node {
char mem;
double mem2;
char mem3;
int mem4;
char mem5;
char mem6;
}NODE;
int main()
{
   NODE * m;
   m->mem3 = 'A';
   printf("%u",&m);

   return 0;
}

I got segmentation fault. When I did like this

#include <stdio.h>

typedef struct node {
char mem;
double mem2;
char mem3;
int mem4;
char mem5;
char mem6;
}NODE;
int main()
{
    NODE * m;
    printf("%u",&m->mem3);

    return 0;
}

I got 16 as output . I don't know how 16 came. It really struggling my mind. Please any one help me to get know what exactly happening. Thanks in advance

回答1:

Because its not allocated any memory

NODE * m = malloc(sizeof(NODE));

// Do stuffs

free(m);

So try this :

int main()
{
    NODE * m = malloc(sizeof(NODE));

    m->mem3 = 'A';
    printf("%u",&m->mem3);

    free(m);

    return 0;
}

Notice :

Int c or c++ if you declare a pointer, some memory is reserved for the pointer (usually on the stack). How ever the pointer is not initialized, meaning that it points to the address corresponding to what was in the respective memory location last. (This is the reason that first section of code is worked).