Search code examples
c++segmentation-faultmallocmemcpy

Segmentation Fault to Deallocate the Memory


I have received the Segmentation Fault (Segfault) because of the free() function in the following code.

How the free() function can be used in this code without receiving the Segmentation Fault?

#include <iostream>
#include <cstring>

using namespace std;

void driver_01(int* buf1, int buf1_size) {

    int* buf2 = (int*)malloc(buf1_size);
    //int* buf2 = new int(buf1_size);
    memcpy(&buf2, &buf1, buf1_size);
    
    int count = 0;
    for (int i = 0; i < buf1_size; i++) {
        if (*(buf2 + i) != 0) {
            count++;
        }
        cout << *(buf2 + i) << endl;
    }
    cout << "Size of buf2: " << count << endl;

    free(buf2);
}

int main() {
    int buf1[8] = { 2, 6, 12, 15, 22, 30, 40, 50 };
    int buf1_size = sizeof(buf1) / sizeof(buf1[0]);

    cout << "Size of buf1: " << buf1_size << endl;

    driver_01(buf1, buf1_size);
    
    return 0;
}

Output:

Size of buf1: 8
2
6
12
15
22
30
40
50
Size of buf2: 8
Segmentation fault

Solution

  • Your use of malloc() and memcpy() are both wrong.

    • You are not allocating enough memory for the buf2 array to copy the values from the buf1 array. You are allocating space for only 8 bytes, not 8 ints.

    • You are copying 8 bytes, not 8 ints, from the wrong source memory address (the address of the buf1 parameter itself rather than the address of the array it points at), and writing them to the wrong destination memory address (the address of the buf2 variable itself rather than the address of the array it points at), thus you are corrupting memory.

    Try this instead:

    void driver_01(int* buf1, int buf1_size) {
    
        int* buf2 = (int*) malloc(sizeof(int) * buf1_size);
        //int* buf2 = new int[buf1_size];
        memcpy(buf2, buf1, sizeof(int) * buf1_size);
        //std::copy_n(buf1, buf1_size, buf2);
      
        int count = 0;
        for (int i = 0; i < buf1_size; i++) {
            if (buf2[i] != 0) {
                ++count;
            }
            cout << buf2[i] << endl;
        }
        /*
        int count = count_if(buf2, buf2 + buf1_size,
            [](int i){ return i != 0; });
        for_each(buf2, buf2 + buf1_size,
            [](int i){ cout << i << endl; });
        */
    
        cout << "Size of buf2: " << count << endl;
    
        free(buf2);
        //delete[] buf2;
    }