Search code examples
cpointersmemcpy

Swapping C variable


As an exercise, I'm trying to swap variable content with a function that takes void pointers as parameters. I cannot figure out why it return always a random value for the first variable.

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

void swap(void* vp1, void* vp2, int size)
{ 
  char buffer[size];
  memcpy(buffer, vp1, size);
  memcpy(vp1, vp2, size);
  memcpy(vp2, buffer, size);
}

void main()
{
  int g1 = 243;
  int g2 = 28;

  printf("g1 before swap = %i\n", g1);
  printf("g2 before swap = %i\n", g2);

  printf("&g1 = %p\n", &g1);
  printf("&g2 = %p\n", &g2);

  swap(&g1, &g2, sizeof(int*));

  printf("-------------------------\n");

  printf("g1 after swap = %i\n", g1);
  printf("g2 after swap = %i\n", g2);

  printf("&g1 = %p\n", &g1);
  printf("&g2 = %p\n", &g2);
}
./swap
g1 before swap = 243
g2 before swap = 28
&g1 = 0x7ffee832072c
&g2 = 0x7ffee8320728
-------------------------
g1 after swap = -399374528
g2 after swap = 243
&g1 = 0x7ffee832072c
&g2 = 0x7ffee8320728

Example is directly taken from this course, pretty interesting though


Solution

  • You are swapping with the wrong size, on your system sizeof (int*) is bigger than sizeof (int).

    As we can see from your output, sizeof (int*) is 8, but sizeof (int) is 4. When copying from g1 to buffer 4 more bytes are fetched which will overwrite the contents of g1 when copying buffer to g2.

    Change the call into

    swap(&g1, &g2, sizeof g1);
    

    If you like to know the size of an object like g1, use sizeof g1.