C语言 有关内存的思考题

来源:互联网 发布:vm共享文件夹mac 编辑:程序博客网 时间:2024/05/17 03:54

1.

void GetMemory(char *p){     p = (char *)malloc(100);}void Test(void){     char *str=NULL;     GetMemory(str);     strcpy(str,"Hello World");     printf(str);}

请问运行Test函数会有什么样的结果?
程序编译可以通过,运行中出现内存错误。
因为GetMemory不能传递动态内存,Test函数中的str一直都是NULL。strcpy(str,”Hello World”);将由于str中没有开辟足够的内存空间而使内存崩溃。

2.

char *GetMemory(void){     char p[] = "Hello World";     return p;}void Test(void){     char *str=NULL;     str = GetMemory();     printf(str);}

请问运行Test函数会有什么样的结果?
程序编译通过,可能显示为乱码。
因为GetMemory返回的是指向“栈内存”的指针,该指针的地址不是NULL,但其原先的内容已经被清除,新内容不确定,可能显示为乱码。

3.

void GetMemory2(char **p,int num){     *p = (char *)malloc(num);}void Test(void){     char *str=NULL;     GetMemory2(&str,100);     strcpy(str,"Hello World");     printf(str);}

请问运行Test函数会有什么样的结果?
程序编译通过,能够正确输出Hello World,但是对于malloc没有free,造成内存泄漏。

4.

void Test(void){     char *str=(char *)malloc(100);     strcpy(str,"Hello");     free(str);     if(NULL != str)     {          strcpy(str,"World");          printf(str);     }}

请问运行Test函数会有什么样的结果?
程序编译通过,但是篡改动态内存区的内容,后果难以预料,非常危险。
因为free(str);之后,str成为野指针,if(NULL != str)语句对str不起作用,在str成为野指针之后,又继续为str指针赋值,可能会缠上难以预料的后果。

具体了解C语言中内存管理可查阅:
C/C++中内存管理相关知识

1 1
原创粉丝点击