Search code examples
cpointersstructsizeofdynamic-allocation

Allocate pointer to struct, but not actual struct


I allocated memory with malloc to pointer to struct but I allocated nothing to actual struct. However I can access/use the struct.

typedef struct A
{
  int w;
  int x;
  int y;
  int z;
}A;

int main(void) 
{
  A* a = malloc(sizeof(A*));  //Here I allocate memory just to pointer to A

  //Why can I do this than?:
  a->z = 10;
  a->w = 456;
  return 0;
}

Why does this work? Is it just coincidence or is it always supposed to work this way? Some notes:

  1. I couldn't do that with non-dynamic allocation

  2. Tested in repl.it


Solution

  • When you do this:

    A* a = malloc(sizeof(A*));
    

    You don't allocate enough memory for an instance of A. So if you read / write any member that happens to sit beyond the bounds of what was actually allocated, you invoke undefined behavior.

    With undefined behavior, you can't accurately predict your program's output. It may crash, it may output strange results, or (in your case) it may appear to work properly. How undefined behavior manifests can change by making a seemingly unrelated modification such as an extra local variable, a call to printf for debugging, or by recompiling with different options.

    Just because a program could crash doesn't mean it will.

    If you use a tool such as valgrind, it can capture when you use memory incorrectly such as in your example.