arrayscswapmemcpygarbage

Garbage value when swapping array with memcpy()


I am trying to make a generic swap function using memcpy() in C. I am getting a garbage value when I try to swap arrays.

This is code below:

#include<stdio.h>
#include<string.h>

typedef struct Student
{
    char a[10];
    int b;
    double c;
}   Student;

void swap(void* one, void* two,size_t size)

{
    char temp[size] ;
    memcpy(temp,two,size); // temp = *two;
    memcpy(two,one,size);//*two = *one;
    memcpy(one,temp,size);//*one = temp;
}

int main()
{
    int i1 = 10, i2 = 20;
    float f1 = 1.6, f2 = 8.9;
    int a1[3] = {1, 2, 3}, a2[3] = {10, 20, 30};
    Student s1 = {"Mark", 42, 5.2}, s2 = {"Bilal", 9, 3};
    swap(&i1,&i2,sizeof(int));
    printf(" i1 = %d \n i2 = %d\n",i1,i2);
    swap(&f1,&f2,sizeof(double));
    printf(" f1 = %f \n f2 = %f\n",f1,f2);
    swap(&a1,&a2,sizeof(a2));
    printf(" a1 = %d %d %d  \n a2 = %d %d %d ",a1[0],a1[1],a1[2],a2[0],a2[1],a2[2]);

}

The output is below:

Enter image description here

I am also getting a garbage value for the array.


Solution

  • The problem is very likely

    swap(&f1,&f2,sizeof(double));
    

    The variables f1 and f2 are of type float, not double. The size of float is commonly four bytes, while the size of double is eight bytes.

    Because you pass the wrong size your memcpy calls will go out of bounds and lead to undefined behavior.

    Use the size of the variables instead:

    swap(&f1,&f2,sizeof f1);
    

    NB: That the value of f2 is printed as zero should be a pretty big hint that the problem lies there.


    Also note that &a1 and &a2 is wrong. Those are pointers to the actual arrays themselves, while you should pass pointers to the first element of the array. The type of both &a1 and &a2 is int (*)[3], but you should pass int *. Instead pass e.g. &a1[0], or just plain a1 as that will decay to a pointer to its first element.