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
}
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);
}
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);
}
char *GetString(void)
{
char p[] = "hello world";
return p;
}
void foo(void)
{
char *str = NULL;
str = GetString(); // str:junk inside
cout<< str << endl;
}
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