Jump to content
  • Advertisement
Sign in to follow this  
NewbieA

Need help on passing malloc pointer

This topic is 4733 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!