Need help on passing malloc pointer

Started by
3 comments, last by NewbieA 18 years, 9 months ago
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);
}

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.
HardDrop - hard link shell extension."Tread softly because you tread on my dreams" - Yeats
You need a pointer to a pointer and assign the malloced value to *pt.
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

Thanks guys, you save my day.
[smile]

This topic is closed to new replies.

Advertisement