Search code examples
cmemory-managementmallocdynamic-memory-allocation

Storing allocated value to allocated array


The code I have is this:

uint8_t* payload = (uint8_t*)malloc(payload_size);
uint8_t* payloads = (uint8_t*)malloc(payload_size * 100);

for(uint8_t i = 0; i < 100; i++ ){

create_payload(payload); //cannot modify 

//myapproach
payloads[i] = payload;

}

And this is not even compiling.

I'd like to store the payload values to the payloads array because the payload variable gets replaced at every iteration.

Is there a simple solution to this?


Solution

  • At first, payloads should point to pointers of uint8_t, not a uint8_t itself (Because you want to store pointers on this data)

    Then, you using same buffer for every payload creation, so you filling payloads with pointer to the same data, you need to allocate new buffer for every payload

    And, at last - size of resulting buffer will be

    size of one entry *pointer* * count of entries
    

    not a

    size of one entry * count of entries
    

    So resulting code will be:

    
    uint8_t** payloads = (uint8_t**)malloc(sizeof(uint8_t*) * 100);
    // uint8_t* payloads[100]; - Will also work
    
    for(uint8_t i = 0; i < 100; i++ ){
        uint8_t* payload = (uint8_t*)malloc(payload_size);
    
        create_payload(payload); //cannot modify 
    
        payloads[i] = payload;
    }
    

    Or, if you wanted to have all payloads to be in same buffer, use malloc to copy payload to output:

    uint8_t* payload = (uint8_t*)malloc(payload_size);
    uint8_t* payloads = (uint8_t*)malloc(payload_size * 100);
    
    for(uint8_t i = 0; i < 100; i++ ){
    
        create_payload(payload); //cannot modify 
    
        memcpy(payloads + i * payload_size, payload, payload_size);
    }