0

I have a struct like this

struct Patient {
    char* name;
    char* address;
    char* socialSecurityNumber;
    char* typeOfExamination;
    bool isExpress;
}

And I have to fill a dynamic array of this struct from a txt file like this: (delimiter: ";")

Andrew;Address street first;123;pulmonary;1
Matthew;Address street second;456;COVID;0
Lisa;Address street third;789;rectum;0

After opening the file and reading the file:

while (fgets(line, 255, (FILE*) fPtr)) {
        char *p = strtok (line, ";");
        patients[i].name=(char*)malloc(sizeof(char*));
        strcpy(patients[i].name, p);

        p = strtok (NULL, ";");
        patients[i].address=(char*)malloc(sizeof(char*));
        strcpy(patients[i].address, p);
        
        ...

        i++;
    }

After the second malloc/strcpy I get a sysmalloc: Assertion failed error

What am I doing wrong?

skinshape
  • 133
  • 7

1 Answers1

0

patients[i].name=(char*)malloc(sizeof(char*)); allocates enough space for a single character pointer, about 4 to 8 bytes. You need to allocate enough space for each character, plus a null byte at the end.

patients[i].name = (char*)malloc(sizeof(char) * (strlen(p)+1));

That will work, but we can slim it down. There's no need to cast malloc. Normally we also multiply the length by sizeof the type, but sizeof(char) is always 1, so it can be omitted.

patients[i].name = malloc(strlen(p)+1);

You can use strdup to do the same thing, but that's a POSIX function not always available. It's often worthwhile to write your own.

patients[i].name = strdup(p);
Schwern
  • 153,029
  • 25
  • 195
  • 336