I’m working with a c++ program that uses multiple buffers and I’m getting a seg fault a few minutes into running the program. I’m unsure of the correct way to go about it. The code that I think is giving me the fault is currently as such:
int *myBuf1, *myBuf2;
myBuf1 = (int*)malloc(sizeof(int) * maxPacketSize);
myBuf2 = myBuf1;
// do work
if(myBuf1) {
free(myBuf1);
}
myBuf1 = NULL;
myBuf2 = NULL;
My first question is: with the assignment ‘myBuf2 = myBuf1’, does myBuf2 allocate a different block of memory with sizeof(int) * maxPacketSize, or is it just a pointer to the same block of memory allocated by myBuf1?
Secondly, should I be freeing myBuf2 as well as myBuf1, then setting both to NULL? Above I’m only freeing myBuf1. OR, is it best to do:
myBuf1 = (int*)malloc(sizeof(int) * maxPacketSize);
myBuf2 = (int*)malloc(sizeof(int) * maxPacketSize);
then free both?
A: No
A: No. One malloc (), one free().
A: Yes, I would strongly encourage setting ALL pointers to NULL.