I'm having some problems trying to free a buffer created in a function from outside that function in C. What I'm doing is to create bufA, do some stuff with it, then call a function which creates bufB, whose length is calculated inside that function. Bytes in bufA are then copied to bufB with some additional bytes added, then the function returns. Some further processing is done with bufB back in main(), then both bufA and bufB are freed. The program runs correctly, but throws an error when free(bufB) is called.
For very much simplified code, I have something like this:
typedef unsigned char BYTE;
// -----
int main(void) {
// -----
BYTE bufA = NULL;
// Specify lenBufA
bufA = calloc(lenBufA, 1);
// Populate bufA with some stuff.
BYTE bufB = NULL;
int lenBufB = myFunction(bufA, &bufB);
// Do something with bufB.
free(bufA);
free(bufB); // <=== Throws an error here.
return 0;
}
Then in myFunction() I may have something like this:
int myFunction(BYTE* inBuf, BYTE** outBuf) {
// Initialization.
// Calculate the length that outBuf will have and put it in outLen.
*outBuf = (BYTE*)calloc(outLen, 1);
// Do stuff with outBuf.
return outLen;
}
inBuf is not specified as constant as some bytes may be changed. calloc() rather than malloc() is used in main() and in the function because I want the bytes in both buffers to be initialized to zero, as a few bytes in both are not given values.
I'm using visual Studio 2022 with Windows 10. Somehow the error caused by free(bufB) must be related to the fact that memory is allocated in the function, not in main(). How is this fixed?