I am trying to constantly read data into a buffer of type unsigned char* from different files. However, I can’t seem to set the buffer to NULL prior to reading in the next file.
Here is only the relevant code:
#include <stdio.h>
#include <fstream>
int
main (int argc, char** argv) {
FILE* dataFile = fopen("C:\\File1.txt", "rb");
unsigned char *buffer = NULL;
buffer = (unsigned char*)malloc(1000);
fread(buffer,1,1000,dataFile);
fclose(dataFile);
dataFile = fopen("C:\\File2.txt", "rb");
buffer = NULL;
fread(buffer,1,1000,dataFile);
fclose(dataFile);
system("pause");
return 0;
}
The error I run into is at the second occurrence of this line: fread(buffer,1,1000,dataFile);
The error I get is:
Debug Assertion Failed!
Expression: (buffer != NULL)
It points me to Line 147 of fread.c which is basically:
/* validation */ _VALIDATE_RETURN((buffer != NULL), EINVAL, 0); if (stream == NULL || num > (SIZE_MAX / elementSize)) { if (bufferSize != SIZE_MAX) { memset(buffer, _BUFFER_FILL_PATTERN, bufferSize); } _VALIDATE_RETURN((stream != NULL), EINVAL, 0); _VALIDATE_RETURN(num <= (SIZE_MAX / elementSize), EINVAL, 0); }
I did Google for ways to get the buffer pointer to NULL and tried the various suggestions, but none seem to work. Anyone can clarify what is the right way to set it to NULL?
Your
bufferis a pointer.When you do this:
you allocate some space in memory, and assign its starting position to
buffer. Remember,bufferholds the address of the beginning of the space, that’s all. When you do this:you have thrown away that address.
EDIT:
C++ style, without dynamic memory:
There’s no need to erase the contents of the buffer. If the cost of allocating and deallocating the buffer with each call is too much, just add
static:It will be overwritten each time.