I have a function that returns a string of a line from a file, but when I execute it, I get a segmentation fault message. Here's the code:
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include "parser.h"
const int MAX_CHAR_PER_LINE = 100;
int main()
{
FILE *h = fopen("/home/test.txt", "r");
char *line = read_line(h);
printf("%s", line);
return 0;
}
int parse(FILE *header)
{
return 0;
}
char* read(FILE *header, int bytes)
{
char *ret_v = (char*) malloc(bytes);
fread((void*) ret_v, 1, bytes, header);
return ret_v;
}
char* read_line(FILE *header)
{
char *line = (char*) malloc(MAX_CHAR_PER_LINE);
char ch = getc(header);
int count = 0;
while (ch != 255 && ch != '\n')
{
line[count] = ch;
ch = getc(header);
count++;
}
line[++count] = '#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include "parser.h"
const int MAX_CHAR_PER_LINE = 100;
int main()
{
FILE *h = fopen("/home/test.txt", "r");
char *line = read_line(h);
printf("%s", line);
return 0;
}
int parse(FILE *header)
{
return 0;
}
char* read(FILE *header, int bytes)
{
char *ret_v = (char*) malloc(bytes);
fread((void*) ret_v, 1, bytes, header);
return ret_v;
}
char* read_line(FILE *header)
{
char *line = (char*) malloc(MAX_CHAR_PER_LINE);
char ch = getc(header);
int count = 0;
while (ch != 255 && ch != '\n')
{
line[count] = ch;
ch = getc(header);
count++;
}
line[++count] = '%pre%';
char *ret_line;
memcpy(ret_line, line, strlen(line));
free(line);
return ret_line;
}
';
char *ret_line;
memcpy(ret_line, line, strlen(line));
free(line);
return ret_line;
}
I do not understand why you are making this mistake, apparently I did everything right. (I.e. Note: I just discovered that the "error" is not in the code, but in the compiler. I compiled with the TCC and the segfault error appeared, but when compiled with gcc the function returned the correct value.