Last active
December 21, 2018 00:17
-
-
Save jasonknight/36dff93cc4b9976703b0284fca111ca1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.