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?

6
  • 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. Commented Oct 16, 2017 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 Commented Oct 16, 2017 at 18:58
  • int* point = malloc(sizeof(int)) this is what @wildplasser means, I think Commented Oct 16, 2017 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. Commented Oct 16, 2017 at 19:08
  • 3
    I suggest avoiding the term "double pointer" unless you're talking about the type double*. Commented Oct 16, 2017 at 19:17

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@AnttiHaapala Edited. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.