Wednesday, December 19, 2007

Allocate memory problems

Some were discussed in former posts. If the parameter of the function is a pointer, don't use it to allocate memory dynamically, the following codes have problem:

void GetMemory(char *p, int num)
{
p = (char *)malloc(sizeof(char) * num);
}
void foo(void)
{
char *str = NULL;
GetMemory(str, 100);// str is still NULL
strcpy(str, "hello"); // wrong
}

The compiler generates a temp pointer _p = p. _p get some memory block but p doesn't. The following 2 codes are correct. The first uses pointer to pointer:

void GetMemory(char **p, int num)
{
*p = (char *)malloc(sizeof(char) * num);
}
void foo(void)
{
char *str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
cout<< str << endl;
free(str);
}

The second uses 'return pointer'

char *GetMemory(int num)
{
char *p = (char *)malloc(sizeof(char) * num);
return p;
}
void foo(void)
{
char *str = NULL;
str = GetMemory(100);
strcpy(str, "hello");
cout<< str << endl;
free(str);
}

Be careful, don't return a pointer with junk, such like following code. p points to junk after the scope.

char *GetString(void)
{
char p[] = "hello world";
return p;
}
void foo(void)
{
char *str = NULL;
str = GetString(); // str:junk inside
cout<< str << endl;
}

The following codes may get the correct answer but it is still wrong. The pointer points to a constant string and it never changes

char *GetString(void)
{
char *p = "hello world!";
return p;
}
void foo(void)
{
char *str = NULL;
str = GetString();
cout<< str << endl;
}

No comments:

Post a Comment