Home > other >  calloc allocatin 0 bytes for a struct field
calloc allocatin 0 bytes for a struct field

Time:12-27

Heyo, I have problem allocating memory for my "database"

i have this struct

typedef struct TPrvek {
    struct TPrvek *parent1;
    struct TPrvek *parent2;

    int id;//key

    char *name;//value
} TPrvek;

typedef struct Database {
    int size;
    struct TPrvek **TField;
} DATABASE;

and I am initializing like this :

void init(DATABASE *db) {
    DATABASE *newDb = (DATABASE *) malloc(sizeof(DATABASE));
    newDb->size = 1000;//initial capacity
    newDb->TField = (TPrvek **) calloc(newDb->size, sizeof(TPrvek *));
    for (int i = 0; i < db->size; i  ) {
        newDb->TField[i] = NULL;
    }
    *db = *newDb;
}

But when i try to insert smth to it, im writing out of allocated memmory and I don't know how to repair it nor what is even wrong snipet of insertion:

    int addPerson(DATABASE *db,
                  int id,
                  const char *name,
                  int id1,
                  int id2) {
        //some checks to make sure ids are in bounds and field for new person is empty
    
        TPrvek *clovek = (TPrvek *) malloc(sizeof(TPrvek));
        
            clovek->name = (char *) malloc(sizeof(name)   1);
            strcpy(clovek->name, name);
            clovek->id = id;
        
            //clovek->parent1 = (TPrvek *) malloc(sizeof(TPrvek));
            //clovek->parent2 = (TPrvek *) malloc(sizeof(TPrvek));I was desperate, this is wrong I think
        
            clovek->parent1 = db->TField[id1];
            clovek->parent2 = db->TField[id2]; 
        
            db->TField[id] = clovek;
//returns 1 if success
    }

and in the main I have simple asserts to check functionality like :

int main(int argc,
         char *argv[]) {
    DATABASE a;     
    init(&a);
    assert (addPerson(&a, 1, "John", 0, 0) == 1);
    assert (addPerson(&a, 2, "Caroline", 0, 0) == 1);
...}

Any ideas? I'm pretty new to c and memory allocating in general, so I would be glad for every bit of help :)

CodePudding user response:

This line is the problem (at least one I see straight away):

clovek->name = (char *) malloc(sizeof(name)   1);

Type of name is char *, and sizeof(char *) is size of pointer - always 8. What you need instead is the length of string, i.e:

clovek->name = (char *) malloc(strlen(name)   1);
  • Related