I have a small project (ed-like text editor for myself. Just want to edit some config files using it) and I have some problems with it.
workspace_file->flc = malloc(sizeof(char *));
workspace_file->flc[0] = malloc(1);
FILE *input_file = fopen(workspace_file->filename, "r");
workspace_file->len = 0;
int line = 0, pos = 0; //int multiplier = 1; //multiplier is a legacy stuff
char fileInputBuffer;
while ((fileInputBuffer = fgetc(input_file)) != EOF) {
if (fileInputBuffer != '\n') {
workspace_file->flc[line] = realloc(workspace_file->flc[line], (pos + 2) * sizeof(char));
workspace_file->flc[line][pos] = fileInputBuffer;
++pos;
} else {
workspace_file->len += 1;
workspace_file->flc[line] = realloc(workspace_file->flc[line], (pos + 2) * sizeof(char));
workspace_file->flc[line][pos] = '\0';
workspace_file->flc = realloc(workspace_file->flc, (line + 2) * sizeof(char*));
line++;
pos = 0;
}
}
This stuff works great with small files (number of lines is less or nearly 130), but after the file becomes big (132+ lines) it drops something like IOT Instruction (core dumped)
. I have no idea what to do. I tried some things, but they didn't work, unfortunately. Compiler - GCC
I tried chunks (char ***
instead of char **
for file content, where for example in char[x]
the x
is chunk number), but chunks didn't work as well, unfortunately.
I work in CLI mode (main idea was to use CLI mode instead of RAW, because I want to just change some config files, but no more). Also tried to change some logical errors: workspace_file->flc[line] = realloc(workspace_file->flc[line], (pos+2) * sizeof(char))
generates one more char in the end of the file in RAM. But even after I wrote workspace_file->flc[line]=realloc(workspace_file->flc[line], (pos+1) * sizeof(char))
instead, it didn't work.
I use per-char write into string, because I need to check if the symbol is '\n'
and do some stuff it the symbol is '\n'
.
malloc()
workspace_file->flc
2 times in the very 1st lines of your code. That's an error. Just pick one and go with it. And also check the return values ofmalloc()
andrealloc()
to ensure the allocations are successful.int fgetc()
returns anint
, sochar fileInputBuffer
should beint fileInputBuffer
. Another: allocating 1 byte of memory is a poor design choice. The unclear code also seems to use bothpos
andlen
to control sizes.char
able to holdEOF
?