I have an inputstream.h header that defines a struct having a string, an int, and a readc function. In this header, I define the function init, receiving as a parameter a string having the absolute directory of a file, and the struct inputstream, in this function I read the file and pass the data to the source variable of the inputstream. Here's the code:
inputstream.h
#ifndef INPUTSTREAM_H
#define INPUTSTREAM_H
#include <stdio.h>
typedef struct
{
char *source; // header source code
int pos;
char (*readc)();
}inputstream;
void init(const char*, inputstream*);
#endif
inputstream.c
#include "inputstream.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
inputstream *is;
char readc()
{
return is->source[is->pos++];
}
void init(const char *file_header, inputstream *stream)
{
memset(stream, 0, sizeof(inputstream));
stream->readc = &readc;
FILE *header = fopen(file_header, "r");
if (header == NULL)
{
printf("Cannot open file\nExiting...\n");
exit(EXIT_FAILURE);
}
fseek(header, 0, SEEK_END);
long lenght = ftell(header);
if (lenght <= 0)
{
printf("Empty file\nExiting...\n");
exit(EXIT_FAILURE);
}
fseek(header, 0, SEEK_SET);
stream->source = (char*) malloc(lenght + 2);
//memset(stream->source, 0, sizeof stream->source);
fread(stream->source, lenght + 1, 1, file_header);
fclose(header);
}
When I run the function init the segmentation fault occurs. I have already debugged and it seems that the problem is in function fread. What's wrong with the code?