I'm trying to read a file and allocating a string in the array when needed but It didn't work correctly.
This is an example of a
file.txt:
1
2
3
4
5
and this is my simplfied program :
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LENGTH 256
char *readLine(FILE *f, size_t *len)
{
char *line = NULL;
int idxToDel;
ssize_t nread;
int mem = 0;
if (f == NULL)
{
return NULL;
}
if (len != NULL)
{
mem = *len;
}
else
{
len = (size_t *)malloc(sizeof(size_t));
*len = 0;
}
if ((nread = getline(&line, len, f)) != -1)
{
idxToDel = strlen(line) - 1;
memmove(&line[idxToDel], &line[idxToDel + 1], strlen(line) - idxToDel);
*len = strlen(line);
return line;
}
else
{
if (nread == -1)
{
*len = mem;
}
free(line);
return NULL;
}
}
char **readFile(const char *filename, size_t *fileLen)
{
char *result;
int idx = 0;
char **array = malloc(1 * sizeof(*array));
if (filename == NULL || fileLen == NULL)
{
return NULL;
}
FILE *f = fopen(filename, "r");
void *newptr;
if (f == NULL)
{
return NULL;
}
while (1)
{
result = readLine(f, fileLen);
if (result == NULL)
break;
else
{
*(array + idx) = malloc(LENGTH * sizeof(char *));
strncpy(*(array + idx), result, strlen(result) + 1);
idx++;
array = realloc(array, idx * sizeof(char **));
}
}
if (*(array + idx) == NULL)
{
*fileLen = 0;
}
*fileLen = idx;
return array;
}
int main()
{
char **numbers;
size_t len = 0;
numbers = readFile("file.txt", &len);
return 0;
}
As an error I get
realloc(): invalid next size
Aborted (core dumped)
What am I doing wrong here ? When debugging the program , the index idx stops at the value 4 and exits afterwards.
len = (size_t *)malloc(sizeof(size_t));in thereadLinefunction?if ((nread = getline(&line, len, f)) != -1){...}else{ if (nread == -1)...might be better written asnread = getline(&line, len, f); if(nread != -1){...}else{ ...because it's easier to read if you don't assign and test a value on the same line - and there's no need to test it twice.