By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,171 Members | 1,037 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,171 IT Pros & Developers. It's quick & easy.

swapping pointers returned by malloc

P: n/a
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;
}

Mar 14 '07 #1
Share this Question
Share on Google+
1 Reply


P: n/a
su**************@yahoo.com, India wrote:
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.

Mar 14 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.