I have some code to read a file byte by byte, and store the data in blocks. I have the blocks separated via dynamically allocated memory. Here is my code:
int ch = NULL;
while (ch != EOF) {
//Read 16-byte blocks of data from a text file or until the EOF flag is found
for (size_t i = 0; i < UINT16_MAX && stream && ((ch = fgetc(stream)) != EOF); i) {
//(void)printf("%c", ch);
*blocks = (char)abs(ch);
}
//Increase allocated memory blocks if the previous has been filled
if (ch != EOF) {
uint32_t* tempMem = realloc(blocks, size * sizeof(uint32_t));
if (tempMem == NULL) {
free(blocks);
(void)printf("Error: could not allocate memory");
return EXIT_FAILURE;
}
blocks = tempMem;
*( blocks) = 0; //zero-initialize new memory location
}
}
With this code, I get a corrupted heap address breakpoint, but if I change the memory access method, like so:
int ch = NULL;
while (ch != EOF) {
//Read 16-byte blocks of data from a text file or until the EOF flag is found
for (size_t i = 0; i < UINT16_MAX && stream && ((ch = fgetc(stream)) != EOF); i) {
//(void)printf("%c", ch);
blocks[size - 1] = (char)abs(ch);
}
//Increase allocated memory blocks if the previous has been filled
if (ch != EOF) {
uint32_t* tempMem = realloc(blocks, size * sizeof(uint32_t));
if (tempMem == NULL) {
free(blocks);
(void)printf("Error: could not allocate memory");
return EXIT_FAILURE;
}
blocks = tempMem;
blocks[size - 1] = 0;
}
}
I get no errors and the code runs fine (albeit with logic errors, but this is an educational project anyways). How come doing array[ index]
works fine, but *( pointer_to_an_array)
breaks everything?
CodePudding user response:
blocks
changes blocks
, after which it is no longer the address of the start of the allocated memory, so it is not the correct address to pass to free
or realloc
.