Sign in to follow this  
NewbieA

Need help on passing malloc pointer

Recommended Posts

Hello, I'm stuck.[help] I play around with pointers and malloc to revise my C, but then i got stuck. Could anyone save me on this? Anyone know how to malloc a block of memory in a function, like the one below, without "return"-ing a pointer?[crying] Thank you~ [grin]
void setmem(char *pt)
{
  pt = (char *) malloc (sizeof(char)*6);
}

int main()
{
  char *pt = NULL;

  setmem(pt);
  strcpy(pt, "Hello");

  printf("\nmy pt=%s", pt);
}

Share this post


Link to post
Share on other sites
You've created a mem leak there, since you won't modify the passed in pointer but merly a stackbased copy of it.

What I'm guessing that you want is a pointer pointer like so

void setmem(char **pt)
{
*pt = malloc( sizeof(char) * 6);
}


and then you could do:

int main()
{
char *pt = NULL;
printf( "pt berfore call:%p\n", pt);
setmem( &pt);
printf( "pt after call:%p\n", pt);
//don't forget to free the memory when you're done
free( pt);
}


hope that was of assistance.

Share this post


Link to post
Share on other sites
Beaten to it...


void setmem(char **pt)
{
*pt = (char *) malloc (sizeof(char)*6);
}

int main()
{
char *pt = NULL;

setmem(&pt);
strcpy(pt, "Hello");

printf("\nmy pt=%s", pt);
}




Make a pointer-to-pointer and your problem is solved. However, you need to dereference it first in order to malloc it.

Toolmaker

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this