一天中遇见两次的笔试题
不得不拿来说说。。。。霸笔也不容易呀!!!
题1:
void Test(void)
{
char *str = (char *) malloc(100);
strcpy(str, "hello");
free(str);
if(str != NULL)
{
strcpy(str, "world");
printf(str);
}
}
int main()
{
Test();
return 0;
}
问题一:用malloc分配内存后并未检测内存分配是否成功
问题二:free(str)后未置str=NULL。此时str为野指针,输出结果为乱码
题2
void GetMemory(char *p)
{
p = (char *)malloc(100);
}
void Test(void)
{
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}
程序崩溃,因为GetMemory并不能传递动态内存,Test函数中的str一直都是NULL,strcpy(str, "hello world");将使程序崩溃。
GetMemory中用malloc分配了内存,但没有检测内存是否分配成功。也没有free掉这片内存,会造成内存泄露。
题3
char *GetMemory(void)
{
char p[] = "hello world";
return p;
}
void Test(void)
{
char *str = NULL;
str = GetMemory();
printf(str);
}
是乱码。因为GetMemory 返回的是指向“栈内存”的指针,该指针的地址不是 NULL,但其原来的内容已经被清除,新内容不可知。
void GetMemory(char **p, int num)
{
*p = (char *)malloc(num);
}
void Test(void)
{
char *str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
}
请问运行Test 函数会有什么样的结果?
分析:
(1)能够输出hello
(2)内存泄漏
浙公网安备 33010602011771号