2

I have a question about a double pointer in C. For example:

int** point = malloc(sizeof(int**));
int* point2 = malloc(sizeof(int*));
*point2 = 5;
*point = point2;
free(point2);
printf("%d", *point);

My question is, if I have a double pointer pointing to another pointer (point2) and I make a free on (point2), the double pointer (point) is going to point to a memory address that has nothing. So I should do * point = NULL?

Juanjoo Tocino
  • 143
  • 1
  • 8
  • yes, that could be a good idea to avoid keeping an invalid pointer ref. Note that you don't need to use malloc for those cases. – Jean-François Fabre Oct 16 '17 at 18:58
  • 2
    `int* point2 = malloc(sizeof(int*));` point2 is an integer pointer; it should point to an int. So, you should allocate `sizeof(int)`, or `sizeof *point2` – wildplasser Oct 16 '17 at 18:58
  • `int* point = malloc(sizeof(int))` this is what @wildplasser means, I think – akshayk07 Oct 16 '17 at 19:01
  • 2
    Your mallocs are indeed wrong. Do instead `int **point = malloc(sizeof *point)` and `int *point2 = malloc(sizeof *point2)` to avoid these errors. – Antti Haapala -- Слава Україні Oct 16 '17 at 19:08
  • Both mean `int** point = malloc(sizeof(int**));` is only correct by mistake and `int* point2 = malloc(sizeof(int*));` allocates storage for a pointer instead of an `int`. Perhaps `int **point = malloc (sizeof *point);` and `int *point2 = malloc (sizeof *point2);` – David C. Rankin Oct 16 '17 at 19:08
  • 3
    I suggest avoiding the term "double pointer" unless you're talking about the type `double*`. – Keith Thompson Oct 16 '17 at 19:17

1 Answers1

2

Strictly speaking, you don't have to assign NULL to *point. However, it is a very good idea to do it anyway, because it helps you distinguish valid pointers from invalid when you debug your program.

the double pointer (point) is going to point to a memory address that has nothing.

Memory always has something in it. However, it's not always under your control, so it may not be legal to read its content.

For instance, when you free point2, the value stored in point is not going to disappear. However, it would become illegal to use that value, as it becomes indeterminate.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523