Search code examples
cmallocfunction-pointersvoid-pointers

Using a function to allocate complex custom data structures


I am trying to allocate memory for certain data structures (array, matrix, custom_array, ...). The problem I think I am facing is that I am not able to cast the proper types to the passed pointers which I initialized to NULL. Keep in mind that I am passing the adresses of the pointers
( init_structs(&ptr1, &ptr2, &ptr3, ...) ):

int init_structures(void* d_decharge,
                    void* d_poubelles,
                    void* e_camions,
                    int m, int n,
                    int *tamp_id, int* file_msg_id)
{
    *d_decharge = (int*)malloc(m * sizeof(int));
    if (*d_decharge == NULL){
        printf("echec malloc dist_decharge\n");
        return 1;
    }

    *d_poubelles = (int**)new_matrix(m);
    if(*d_poubelles == NULL){
        printf("echec malloc dist_decharge\n");
        return 1;
    }

    key_t key_tamp = ftok("./src/main.c", 64);
    int id = shmget(key_tamp, sizeof(camion_t) * n, 0666 | IPC_CREAT);
    if (id == -1){
        printf("echec creation du tampon etats_camions, error[%s]\n", strerror(errno));
        return 1;
    }
    *tamp_id = id;
    *e_camions = (camion_t*)shmat(*tamp_id, NULL, 0);
    
    key_t key_msg = ftok("./src/main.c", 64);
    id = msgget(key_msg, 0666 | IPC_CREAT);
    if(id==-1){
        printf("echec creation de la file de messages Faffec, error[%s]\n", strerror(errno));
        return 1;
    }
    *file_msg_id = id;
    return 0;
}

I tried declaring the proper types but that just runs into a passed by copy problem.


Solution

  • The problem I think I am facing is that I am not able to cast the proper types to the passed pointers [...]. I am passing the adresses of the pointers ( init_structs(&ptr1, &ptr2, &ptr3, ...) ).

    You could perform enough casting to make your function work, but why? Most casting for other than arithmetic purposes is symptomatic of poor design. In this case, you are passing (apparently) an int **, an int *** (yuck), and a camion_t ** to init_structures(), and relying on those types, but the function is receiving them as type void *. To work with that, you would need to convert the pointers back to their original types inside the function, but it would be so much cleaner and easier then to just pass them as their original types:

    int init_structures(int **d_decharge,
                        int ***d_poubelles,
                        camion_t **e_camions,
                        int m, int n,
                        int *tamp_id, int* file_msg_id) // ...
    

    Of course, that assumes that those are in fact the correct types, as they sure should be. But if the original ptr1, ptr2, and ptr3 are instead all void * then

    1. WTH?
    2. You would want to use type void ** for the function parameters instead of void * or the above pointer types.