Using a pointer after freeing using free ()

I am having problems with the following type of code:

int* myPointer1 = malloc(50 * sizeof(int));
int* myPointer2 = malloc(50 * sizeof(int));
free(myPointer1);
myPointer1 = myPointer2;
myPointer1[0] = 3;

I get a segmentation error. What is the problem?

+5
source share
2 answers

The problem is not in this code. The scanned fragment looks correct and works fine in isolation.

+3
source

Your code is correct, there is nothing wrong with it, but you are used to testing the return value of the malloc () function, if it is NULL, this will create a problem in your program, in our case, malloc () memory allocation does not work

+2
source

All Articles