[C语言]——动态内存经典笔试题分析

时间:2024-04-14 08:56:41

目录

一.题目1

1.运行结果

2.分析

3.问题所在

4.更正

二.题目2 

1.运行结果

2.分析

3.问题所在

4.更正

三.题目3

1.问题所在

2.更正:

四.题目4


一.题目1

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

1.运行结果

2.分析

3.问题所在

 
4.更正

void GetMemory(char **p)
 {
   *p = (char *)malloc(100);
 }
 void Test(void)
 {
   char *str = NULL;
   GetMemory(&str);
   strcpy(str, "hello world");
   printf(str);
   free(str);
   str=NULL;
 }

二.题目2 

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

1.运行结果

2.分析

str为指针变量

3.问题所在

这是一个返回栈空间地址的问题,str虽然能通过地址找到所对应的空间,但是一旦出GetmMemory函数中,空间已经还给操作系统,空间已经没有使用权限,此时的str就是野指针,print调用的时候,会将绿色区域覆盖

4.更正

char *GetMemory(void)
 {
   static char p[] = "hello world";
   return p;
 }
 void Test(void)
 {
   char *str = NULL;
   str = GetMemory();
   printf(str);
 }

代码简化: 

 

三.题目3

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

1.问题所在

存在内存泄漏的问题

2.更正:

void GetMemory(char **p, int num)
 {
  *p = (char *)malloc(num);
 }
 void Test(void)
 {
  char *str = NULL;
  GetMemory(&str, 100);
  strcpy(str, "hello");
  printf(str);
  fre(str);
  str=NULL;
 }

四.题目4

void Test(void)
 {
   char *str = (char *) malloc(100);
   strcpy(str, "hello");
   free(str);  //此步骤后,str为野指针了
   if(str != NULL)
 {
   strcpy(str, "world"); //非法访问
   printf(str);
 }
 }

更正:

void Test(void)
 {
   char *str = (char *) malloc(100);
   strcpy(str, "hello");
   free(str);  
   str=NULL;//应该手动置为空
   if(str != NULL)
 {
   strcpy(str, "world"); 
   printf(str);
 }
 }