Verify correct usage of malloc and free.

Hi I am following the Stanford programming paradigms series. We have a function (that works) for a generic swap.

1
2
3
4
5
6
7
void a_swap(void *vp1, void *vp2, int size)
{
    char buffer[size]; // 
    memcpy(buffer, vp1, size); // copy vp1 to buffer for 'size' given
    memcpy(vp1, vp2, size); // copy from vp2 to vp1
    memcpy(vp2, buffer, size); // copy from buffer to vp1
}


I rewrote this to use malloc and wanted to have someone double check I did this correctly or not.
1
2
3
4
5
6
7
8
9
void a_swap(void *vp1, void *vp2, int size)
{
    char *buffer;
    buffer = (char *)malloc(sizeof(char)*size);
    memcpy(buffer, vp1, size); // copy vp1 to buffer for 'size' given
    memcpy(vp1, vp2, size); // copy from vp2 to vp1
    memcpy(vp2, buffer, size); // copy from buffer to vp1
    free(buffer);  
}
Last edited on
1. malloc() may fail, so you may better check its return value against NULL (or std::nullptr).

2. size may be negative, so better do declare it unsigned.

3. If programming for reliable system you may want to test vp1 and vp2 against NULL.

4. Your function isn't type save. Better use templates to assert the same data type for vp1, vp2 and buffer.

5. Think about defining more reliable data structures, which manage their attributes in a consistent way and protect them against uncontrolled access, like f.e. std::string.
Thank you for you input. The series (video lectures) is getting into how low level memory works and we are just starting to create "generic functions" in place of using templates to heighten our understanding of how programs work in memory.

Thanks again!
Topic archived. No new replies allowed.