I am writing a code which reads a text file in to chunks of memory of max 1024 bytes. For this i am creating a linked list with 1016 bytes of data and a pointer to the previous node. My code executes perfectly and dynamically allocates and uses data, as well as linking back perfectly. The problem arrises when it has to create the fourth node. When i increase the malloc size manually (and set it to 1200 for example) it creates 48 nodes before crashing, suggesting the struct size increases. But when i print sizeof(*memory) or sizeof(struct Chunk) the size stays 1024 bytes.
I get the following error caused by the line where i use malloc:
malloc.c:2392: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed. Aborted (core dumped)
my code is as following:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, char **argv) {
// declare variables
int const CHUNK_SIZE = 1024;
int chunk_index = 0;
struct Chunk {
struct Chunk *previous;
int data[(CHUNK_SIZE-sizeof(struct Chunk*))/sizeof(int)];
};
struct Chunk* memory = (struct Chunk *)malloc(sizeof(struct Chunk));
struct Chunk* temp;
// check if the amount of arguments is as expected
if (argc!=2) {
printf("Usage: reverse <filename>\n");
return -1;
}
// check if the file can be opened
FILE *fp;
fp = fopen(argv[1], "r");
if (fp==0) {
printf("Cannot open file!\n");
return -1;
}
// start program
do {
memory->data[chunk_index] = fgetc(fp);
chunk_index++;
if ( chunk_index*sizeof(int) > CHUNK_SIZE-sizeof(struct Chunk*) ) {
temp = (struct Chunk *)malloc(CHUNK_SIZE);
temp->previous = memory;
memory = temp;
}
}
while(memory->data[(chunk_index-1)]!=EOF && chunk_index<CHUNK_SIZE-sizeof(char*));
}