In this swap function, free() is not working in the last line for temp variable, what am I doing wrong.

#include <stdio.h>
# include <stdlib.h>
void swap (int* x,int* y);
int main (void)
    int a = 1;
    int b = 2;
    printf("value of a and b is %i,%i respectively\n", a,b);
    printf ("Swapping!\n");
    swap (&a,&b);
   printf("value of a and b is %i,%i respectively\n", a,b);


void swap (int* x,int* y)
    int temp=*x;
     free (temp);

int temp is not dynamically allocated, you only free() dynamically allocated or malloced memory. int temp, which is static, gets freed from memory as soon as you exit its scope.

| improve this answer | |
  • Please elaborate dynamically allocated memory. – Ahmed Raza Sep 30 '16 at 18:13
  • pset4 will heavily involve pointers and dynamic memory. However, when you type int x = 10 you are declaring statically allocated memory, which will "free" itself when you leave the scope of the function or loop it is declared in. Dynamically allocated memory on the other hand, is requested by use of the malloc() function. Why use malloc when you have to free it then? You use it if you don't want the memory the be freed automatically, or if you want to declare a lot of memory, lets say more than a megabyte. – Martin Kleiven Sep 30 '16 at 19:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .