Search code examples
cmallocdynamic-memory-allocation

Could you use the memory allocated by one call of malloc for various variable types?


im currently learning about dynamically using memory and i was wondering, could you allocate lets say 40 bytes with one call of malloc and use like 16 of them for int variables and the rest 24 for doubles? Im asking this because i know that i have to cast the pointer type to use malloc without warnings. So if i used a void pointer could i do something like what i mentioned? Thanks in advance.


Solution

  • ... could you allocate lets say 40 bytes with one call of malloc and use like 16 of them for int variables and the rest 24 for doubles?

    Yes, with some limitations.

    The pointer returned by malloc() and friends is properly aligned for all standard object types.

    The trick: is the address for the 2nd type (double in OP's case), properly aligned for double if it is 16 bytes away? Likely yes in OP's case, but maybe not if the BYTES_FOR_INT was say 20 and not 16.

    A convenient approach is to use a struct.

    #define BYTES_FOR_INT    16
    #define BYTES_FOR_DOUBLE 24
    struct {
       int i[BYTES_FOR_INT/sizeof(int)];
       double d[BYTES_FOR_DOUBLE/sizeof(double)];
    } *st = malloc(sizeof *st);`
    #define BYTE_TOTAL (sizeof *st)
    

    The above may allocate other than BYTES_FOR_INT + BYTES_FOR_DOUBLE bytes, depending on their values and type alignment needs.

    To fix the allocation to BYTE_TOTAL (40) and BYTES_FOR_INT to various values 2-32 takes more work to determine BYTES_FOR_DOUBLE. Padding needs to be considered when BYTES_FOR_INT, BYTES_FOR_DOUBLE, BYTE_TOTAL are not convenient multiples of the size of double..


    i know that i have to cast the pointer type to use malloc without warnings

    No. Casting is not needed here in C. The void * returned by malloc() converts to other object pointer types with no issues.