0

I need to use both malloc and realloc and am confused how to do it.

Assuming that the input file looks something like this:

a *b c
a
*a b *c

and I have structs set up as so:

typedef struct Unit {
    bool hasAstericks;
    char letter;
} unit;

typedef struct Line {
    struct unit clause[4]
} line;

Is it possible to create a struct of type unit from each letter add them to an array in struct Line based off of the line they are on? I've tried using loops but couldn't create structs on the fly with them.

This is what I have tried:

int c;
filename = argv[1];
char *filename;
FILE *fp = fopen(filename, "r");  
filename = (char *)malloc(size);

do {
    c = fgetc(fp);
    inputFile = (char *)realloc(inputFile, size + 1);
    inputFile[n] = c;
    n++;
    size++;
} while (c != EOF);
chqrlie
  • 98,886
  • 10
  • 89
  • 149
liamkr
  • 35
  • 5

1 Answers1

2

Your do/ while loop attempts to read the file into a array of char which you reallocate for each additional byte read from he file.

Yet you should test for end-of-file before storing the byte into the array.

Also it might be best to set a null terminator at the end of the array when you are done, so the array should have size + 1 bytes.

Here you code modified and encapsulated in a function to read the file:

char *read_file(const char *filename) {
    FILE *fp = fopen(filename, "r");  
    if (fp == NULL)
        return NULL;
    size_t size = 0;
    char *p = malloc(size + 1);
    if (p != NULL) {
        int c;
        while ((c = getc(fp)) != EOF) {   
            char *newp = realloc(p, size + 2);
            if (newp == NULL) {
                free(p);
                p = NULL;
                break;
            }
            p = newp;
            p[size] = c;
            size++;
        }
        if (p) {
            p[size] = '\0';  set a null terminator: make p a C string.
        }
    }
    fclose(fp);
    return p;
}
chqrlie
  • 98,886
  • 10
  • 89
  • 149