Search code examples
c++memory-managementdynamic-allocation

C++ program Exits when deletes an char array


There is a problem in deleting the elements of my array. You can see some of my code below.

after second running of delete[] payload[x].data at the second for loop, the program exits.

    struct s_payload{
        u_char data[300];
    }
    .
    .
    u_char sample[300] ="Lorem ipsum dolor sit amet, eu mea laudem impetus.";
    int _bufferSizeConnection = 1000;
    int testCounter = 0;
    s_payload* activeBuffer = new s_payload[_bufferSizeConnection];
    for (;;) {
        for (long int counter = 0; counter < _bufferSizeConnection; counter++) {        
            memcpy(activeBuffer[counter].data, sample, 299);
        }
        //_buffersConnection is std::queue
        _buffersConnection.push(activeBuffer);
         testCounter += 1;
        if (testCounter == 15) {
            LOG_INFO(">testcounter %d", testCounter);
            break;
        }            
        activeBuffer = new s_payload[_bufferSizeConnection];                       
    }        
    for (int i = 0; i < 15; i++) {
        //taking one of the activeBuffer from _buffersConnection
        s_payload* payload = _buffersConnection.wait_and_pop();         
        for (int x = 0; x < _bufferSizeConnection; x++) {
            u_char* current= payload[x].data;
            delete[] payload[x].data;   //Exit at the second running of this line;
        }
        delete[] payload;
    }

what is wrong with this piece of code? Thanks in advance.


Solution

  • You have said activeBuffer = new s_payload[...], so you could legitimately say delete[] activeBuffer. However, data is an array, not a pointer, within each s_payload element of activeBuffer. Therefore, you don't need to delete payload[x].data — whenever you delete payload[x] or delete[] payload, data will also be gone.

    However, I would recommend rethinking your approach rather than trying to patch what you have. You are pushing and popping arrays of fixed-size buffers — is that really necessary? Could you just push and pop std::strings or std::vector<unsigned char>s, and not have to worry as much about your memory management? A std::vector can hold an arbitrary amount of data, for example.

    Let the library do as much of the work as possible so you won't have to!