0
#include<stdio.h>
#include<stdlib.h>
int main(){
  int* a = NULL;
  int* b = a;
  b = (int*)malloc(sizeof(int));
  *b = 10;
  printf("%d, %d", *a, *b);
  return 0;
}

With the code above, I found that although I change the value that b dereferences, the value that a dereferences does not change. Can someone explains why? I thought they should change together.

ZEWEI CHU
  • 427
  • 1
  • 5
  • 15
  • They are not associated. Anyway, `b` was given the value of `a` and then overwritten by the return value from `malloc`. – Weather Vane Feb 28 '18 at 23:46
  • 1
    a points to null, you assign a to b, now b points to null also, you point b to some memory you allocate then change the value stored there, a still points to null. – Retired Ninja Feb 28 '18 at 23:47
  • Oh yeah that makes sense. – ZEWEI CHU Feb 28 '18 at 23:47
  • 1
    [Do not cast `malloc`](http://stackoverflow.com/q/605845/995714) and don't forget to check if `malloc` returns `NULL` and to free the requested memory with `free(b)`. – Pablo Feb 28 '18 at 23:49

1 Answers1

2

After b = (int*)malloc(sizeof(int));, b points to the block of memory you just allocated and a still contains NULL.
When you do *b = 10; you store a 10 in the block of memory you allocated. Still, a doesn't point to anything.

Since a is never made to point to anything, the *a in the printf doesn't make any sense.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
David Schwartz
  • 179,497
  • 17
  • 214
  • 278