Hello,
I have written a code to swap two variables of generic types....
I am able to swap numeric values correctly... but when i try to work with character arrays it is swapping but some characters are missed...
Here is the code..
Code:
/***This is generic swap function implementation, which swaps two variables of any data types
But it uses dynamically allocated buffer rather than stack buffer.. ***/
#include<stdio.h>
#include<stdlib.h>
void swap(void *, void *, int);
int main()
{
int a = 10, b = 20;
char *s1 = strdup("this is new ........!");
char *s2 = strdup("im gonna sleep..");
printf("\n Before swap\n");
printf(" a = %d\n b = %d\n",a,b);
swap(&a, &b, sizeof(int));
printf("\n After swap\n");
printf(" a = %d\n b = %d\n",a,b);
printf("\n Swapping strings\n");
printf("Before Swap\n");
printf(" s1 = %s\n", s1);
printf(" s2 = %s\n", s2);
swap(s1, s2, sizeof(char *));
printf(" After Swap\n");
printf(" s1 = %s\n", s1);
printf(" s2 = %s\n", s2);
}
//accepts pointer to two variables and their size.
void swap(void *vp1, void *vp2, int size)
{
//temp variable equivalent..a buffer
char *buffer = (char *)malloc(size);
//memcpy copies bits from one location to another, memcpy(source, destination, size)
memcpy(buffer, vp1, size);
memcpy(vp1, vp2, size);
memcpy(vp2, buffer, size);
//now we are done so we need to free dynamically allocated memory
free(buffer);
}
And also when is declare strings without strdup.. while swapping it gives seg fault... as im moving addresses not manipulating contents of those address then why it is giving seg fault...??
Thnx!!