swapping pointers returned by malloc

S

subramanian100in

Will the following code always work ?

#include <stdio.h>
#include <stdlib.h>

# define SIZE 50

void myswap(char **name1, char **name2);

int main(void)
{
char *s1;
char *s2 ;

s1 = malloc(SIZE);

if (s1 == NULL)
{
printf("malloc failed\n");
exit(EXIT_FAILURE);
}

s2 = malloc(SIZE);

if (s2 == NULL)
{
free(s1);
s1 = NULL;
printf("malloc failed\n");
exit(EXIT_FAILURE);
}

printf("Before swapping: s1 = %p s2 = %p\n", (void *)s1, (void
*)s2);

myswap(&s1, &s2);

printf("After swapping: s1 = %p s2 = %p\n", (void *)s1, (void
*)s2);

free(s1);
s1 = NULL;
free(s2);
s2 = NULL;

return 0;
}

void myswap(char **name1, char **name2)
{
char *temp;

temp = *name1;
*name1=*name2;
*name2=temp;
}
 
S

santosh

Will the following code always work ?

#include <stdio.h>
#include <stdlib.h>

# define SIZE 50

void myswap(char **name1, char **name2);

int main(void)
{
char *s1;
char *s2 ;

s1 = malloc(SIZE);

if (s1 == NULL)
{
printf("malloc failed\n");
exit(EXIT_FAILURE);
}

s2 = malloc(SIZE);

if (s2 == NULL)
{
free(s1);
s1 = NULL;

Totally redundant.
printf("malloc failed\n");
exit(EXIT_FAILURE);
}

printf("Before swapping: s1 = %p s2 = %p\n", (void *)s1, (void
*)s2);

myswap(&s1, &s2);

printf("After swapping: s1 = %p s2 = %p\n", (void *)s1, (void
*)s2);

free(s1);
s1 = NULL;
free(s2);
s2 = NULL;

return 0;
}

void myswap(char **name1, char **name2)
{
char *temp;

temp = *name1;
*name1=*name2;
*name2=temp;
}

Yes. It's the pointer *value* that's important, when you pass it to
free, (i.e. it must be a value previously returned by *alloc), not the
actual pointer object itself, as long as it's of a compatible type.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,954
Messages
2,570,116
Members
46,704
Latest member
BernadineF

Latest Threads

Top