Skip to content

Instantly share code, notes, and snippets.

@jasonknight
Last active December 21, 2018 00:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonknight/36dff93cc4b9976703b0284fca111ca1 to your computer and use it in GitHub Desktop.
Save jasonknight/36dff93cc4b9976703b0284fca111ca1 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <stdio.h>
int main (int argc, char** argv) {
int *x = (int*)malloc(sizeof(int));
*x = 3;
int *y = x;
printf("x: %d, y:%d\n",*x,*y);
free(x);
printf("x: %d, y:%d\n",*x,*y);
free(y);
}
// Or did you mean
#include <stdlib.h>
#include <stdio.h>
int main (int argc, char** argv) {
int *x = (int*)malloc(sizeof(int));
*x = 3;
int **y = (int**)malloc(sizeof(int*));
*y = x;
printf("x: %d, y:%d\n",*x,*(*y));
free(x);
printf("x: %d, y:%d\n",*x,*(*y));
free(y);
}
@jasonknight
Copy link
Author

jasonknight commented Dec 21, 2018

In the first case you don't have to free y (it causes a double free) because y = x; in the second case, y is allocated (to hold a pointer to int) and so must be freed. Hence no error in the second one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment