I have this code which is supposed to swap two values inside a_ptr and b_ptr:
// swaps two values inside two variables of any type
void swap(void *a_ptr, void *b_ptr)
{
size_t size = sizeof(void *);
void *tmp = malloc(size);
memcpy(tmp, a_ptr, size);
memcpy(a_ptr, b_ptr, size);
memcpy(b_ptr, tmp, size);
free(tmp);
// char wot0 = 0;
// char wot1 = 0;
// swap(&wot0, &wot1);
}
int main(){
long a = -7;
long b = 99999999;
printf("A: %ld, B: %ld\n", a, b);
swap(&a, &b);
printf("A: %ld, B: %ld\n", a, b);
printf("\n");
short c = -9;
short d = 11111;
printf("C: %hd, D: %hd\n", c, d);
swap(&c, &d);
printf("C: %hd, D: %hd\n", c, d);
printf("\n");
char ca = 'a';
char cx = 'x';
printf("CA: %c CX: %c\n", ca, cx);
swap(&ca, &cx);
printf("CA: %d CX: %c\n", ca, cx);
printf("\n");
char *str0 = "Hello, ";
char *str1 = "World!";
printf("STR0: %s STR1: %s\n", str0, str1);
swap(&str0, &str1);
printf("STR0: %s STR1: %s\n", str0, str1);
printf("\n");
return 0;
}
However the output is:
A: -7, B: 99999999
A: 99999999, B: -7
C: -9, D: 11111
C: -7, D: -9
CA: a CX: x
CA: -9 CX: a
STR0: Hello, STR1: World!
STR0: World! STR1: Hello,
It successfully swaps a
and b
, and then somehow replaces c
with b
, and ca
with d
, how's that even possible?
Also, uncommenting these lines:
// char wot0 = 0;
// char wot1 = 0;
// swap(&wot0, &wot1);
Leads to a segfault, why?
EDIT:
I think I didin't convey my intentions very well. That I basically want to do is swap pointers so that a_ptr
points to value inside b
, and b_ptr
points to value inside a
, I don't want to actually copy the values themselves and I think I achieved that somewhat successfully, strings of different lengths (for examples "Foo"
and "Hello, World!"
) get swapped without any issues, I tested that, however I don't understand why some variables don't get swapped and actually point to values outside of that I passed into the function