Reputation: 13
So I have this really weird problem. I have a Swap() function to swap 2 variables of any type:
int Swap(void *item1, void *item2, size_t size) {
void *temp_tab;
if (sizeof(item1) != sizeof(item2)) return 2;
temp_tab = malloc(sizeof(item1) * size);
if (NULL == temp_tab) return 1;
memcpy(temp_tab, item1, sizeof(item1));
memcpy(item1, item2, sizeof(item2));
memcpy(item2, temp_tab, sizeof(temp_tab));
free(temp_tab);
return 0;
}
And I'm using it in my main program like this:
int main(int argc, char *argv[]) {
int a = 9;
int b = 5;
int c = 2;
int d = 6;
int result;
printf("A: %d\nB: %d\nC: %d\nD: %d\n", a, b, c, d);
result = Swap(&a, &b, sizeof(int));
printf("%d\n", result);
printf("A: %d\nB: %d\nC: %d\nD: %d\n", a, b, c, d);
return 0;
}
The problem is the output: A: 5 B: 9 C: 5 D: 6
Somehow my Swap() function is accessing my c variable - I assume it has something to do with memory violation, but I have no clue how to deal with this. Any help would be very appreciated.
PS: result = 0
Upvotes: 1
Views: 83
Reputation: 409432
sizeof
on a pointer returns the size of the pointer, not what it might point to. So the comparison sizeof(item1) != sizeof(item2)
makes no sense as it will always be false.
And this sizeof
of a pointer problem is the root cause of your problem: You allocate too much memory and always copy the size of a pointer instead of the size of the data (which will lead to undefined behavior if the size of a pointer is different from the actual size of the data).
You have the size of the data (in bytes) with the size
argument. You need to use that for your allocation and copying:
temp_tab = malloc(size);
memcpy(temp_tab, item1, size);
memcpy(item1, item2, size);
memcpy(item2, temp_tab, size);
Upvotes: 6