Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

c - free a double pointer

I created a 2-D matrix using double pointer like that:

int** pt; pt = (int*) malloc(sizeof(int)*10);

I know that a pointer is freed like that

free(ptr);

How can we free the double pointer?

What if we print something and later freed that memory and exit the program? Does the final memory consist of that which we used or it will be same as initial?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Say you have a matrix mat

int** mat = malloc(10 * sizeof(int*));
for (int i=0; i<10; ++i) {
  mat[i] = malloc(10 * sizeof(int));
}

then you can free each row of the matrix (assuming you have initialized each correctly beforehand):

for (int i=0; i<10; ++i) {
  free(mat[i]);
}

then free the top-level pointer:

free(mat);

For your second question: if you allocate memory and use it, you will change that memory, which will not be "reverted" even if you free it (although you will not be able to access it reliably/portably any more).

Note: the top-level malloc is using sizeof(int*) as you are allocating pointer-to-ints, not ints -- the size of int* and int are not guaranteed to be the same.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...