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:
I am also getting a garbage value for the array.

The problem is very likely
The variables
f1andf2are of typefloat, notdouble. The size offloatis commonly four bytes, while the size ofdoubleis eight bytes.Because you pass the wrong size your
memcpycalls will go out of bounds and lead to undefined behavior.Use the size of the variables instead:
NB: That the value of
f2is printed as zero should be a pretty big hint that the problem lies there.Also note that
&a1and&a2is 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&a1and&a2isint (*)[3], but you should passint *. Instead pass e.g.&a1[0], or just plaina1as that will decay to a pointer to its first element.