开发者

Using a pointer after freeing it using free()

I'm getting 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'm getting a segmentation fault. What's the problem?


The problem isn't in this code. The snippet you posted appears to be correct, and works fine in isolation.


Your code is correct their is nothing wrong in it, but you make a habit of testing the return value of malloc() function, if it is NULL it will create problem in your program, in our case the memory allocation by malloc() function is failed

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜