Getmemory的几个经典的关于内存的问题
void GetMemory1(char *p)
{
p = (char *)malloc(100);
}
void Test1(void)
{
char *str = NULL;
GetMemory1(str);
strcpy(str, "hello world");
printf(str);
}
char *GetMemory2(void)
{
char p[] = "hello world";
return p;
}
void Test2(void)
{
char *str = NULL;
str = GetMemory2();
printf(str);
}
char *GetMemory3(void)
{
return "hello world";
}
void Test3(void)
{
char *str = NULL;
str = GetMemory3();
printf(str);
}
void GetMemory4(char **p, int num)
{
*p = (char *)malloc(num);
}
void Test4(void)
{
char *str = NULL;
GetMemory3(&str, 100);
strcpy(str, "hello");
printf(str);
}
void Test5(void)
{
char *str = (char *) malloc(100);
strcpy(str, "hello");
free(str);
if(str != NULL)
{
strcpy(str, "world");
printf(str);
}
}
void Test6()
{
char *str=(char *)malloc(100);
strcpy(str, "hello");
str+=6;
free(str);
if(str!=NULL)
{
strcpy(str, "world");
printf(str);
}
}