Nikita Nikita - 1 year ago 147
C Question

*** Error in `./recover': free(): invalid next size (normal)

These code is not working!
It have to read 512-byte blocks until ending of file!

  • valgrind said that all ok!

  • allocated data are freeing at the end

* Error in `./recover': free(): invalid next size (normal): 0x09e89170 *
Aborted (core dumped)

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#define B_SIZE 512

char* getTitle (int c);

int main(int argc, char* argv[])

long size;
uint32_t *data;

// open file

FILE* file = fopen("card.raw", "r");

if (!file) {
fprintf(stderr, "Unable to open/create file\n");
return 1;

fseek(file, 0, SEEK_END);
size = ftell(file);
fseek(file, 0, SEEK_SET);

if (!(data = malloc(512))) {
fprintf(stderr, "Failed to allocate memory\n");
return 1;

while(true) // until end
// read 512 block
if (ftell(file) >= size-2048)

fread(data, B_SIZE, 128, file);

printf("%ld, (%li)\n", ftell(file), size);


// close all files
return 0;

Answer Source

You read B_SIZE * 128(512 * 128 = 64k) bytes into a buffer of only 512 bytes. That will write out of bounds of the allocated memory and lead to undefined behavior.

If you want to read only 512 bytes at a time, then do e.g.

fread(data, 1, B_SIZE, file);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download