So I've combed through this thing pretty thoroughly using printf statements (on mobile) and have narrowed the location of the error down to the nested if (ret == EOF) statement in the read_file function. The data is successfully copied but segfaults on exit of the function. Any chance someone might be able to take a look for me?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BYTES 1024
typedef int8_t byte;
typedef struct file_buffer {
char * file_name;
void * raw_data;
uint64_t file_size;
uint64_t max_size;
uint64_t temps_copied;
uint16_t bytes_in_temp;
uint8_t filled;
FILE * fp;
} FB;
void * open_file(const char * file_name);
static FB * new_buffer(const char * file_name);
static void read_file(FB * fb, FILE * fp);
static void copy_buffer(FB * fb, byte * temp, const int size);
static void check_size(FB * fb, const int size);
int main()
{
open_file("./src/MOCK_DATA.csv");
return 0;
}
void * open_file(const char * file_name)
{
FILE * fp;
fp = fopen(file_name, "rb");
//
FB * buffer = new_buffer(file_name);
read_file(buffer, fp);
return buffer->raw_data;
}
static FB * new_buffer(const char * file_name)
{
FB * fb = calloc(1, sizeof(FB));
//
fb->raw_data = calloc(MAX_BYTES, sizeof(byte));
//
size_t name_size = strlen(file_name) + 1;
fb->file_name = malloc(sizeof(char) * name_size);
//
memcpy(fb->file_name, file_name, name_size);
return fb;
}
static void read_file(FB * fb, FILE * fp)
{
byte temp[MAX_BYTES];
byte nb = 0;
int i = 0;
int j = 0;
int ret;
while (ret = (nb = (fgetc(fp))))
{
if ((ret == EOF) || (j == (MAX_BYTES - 1)))
{
if (ret == EOF) {
copy_buffer(fb, &temp[0], i);
return;
}
else {
copy_buffer(fb, &temp[0], i);
fb->bytes_in_temp = 0;
j = 0;
i = i + 1;
}
}
fb->bytes_in_temp);
temp[j] = nb;
fb->bytes_in_temp++;
j = j + 1;
}
}
static void copy_buffer(FB * fb, byte * temp, const int size)
{
check_size(fb, size);
int start = MAX_BYTES * size;
memcpy(&fb->raw_data[start], temp, fb->bytes_in_temp);
}
static void check_size(FB * fb, const int size)
{
if (fb->temps_copied < size)
{
void * temp = realloc(fb->raw_data, (MAX_BYTES + fb->max_size) * sizeof(byte));
fb->raw_data = temp;
fb->temps_copied = size;
fb->max_size += MAX_BYTES;
}
}
#include <stdint.h>, implement error checkfopen(),fb->bytes_in_temp)is a syntax error (and does nothing if the)is removed), ` memcpy(&fb->raw_data[start], temp, fb->bytes_in_temp);` dereferences a void pointer. You rely on a particular file we don't have so can't test this for you. Run it in a debugger, if that doesn't enlight valgrind to find heap corruption.open_file()a return avoid *raw_databut caller cannot tell how much data is being returned.