当前位置:   article > 正文

C#动态内存管理笔试题_c#笔试题

c#笔试题

题目一:

  1. void GetMemory(char *p)
  2. {
  3. p = (char *)malloc(100);
  4. }
  5. void Test(void)
  6. {
  7. char *str = NULL;
  8. GetMemory(str);
  9. strcpy(str, "hello world");
  10. printf(str);
  11. }
  12. int main()
  13. {
  14. Test();
  15. return 0;
  16. }

程序运行:

 

解析:

调用Test函数,在Test函数里str为空指针。然后调用GetMemory函数,GetMemory函数中*p为形参,形参在GetMemory函数调用完后释放,*p释放后没有指针指向malloc开辟的内存地址,造成内存泄漏。形参不改变实参,*str仍是空指针。将"hello world"拷贝放到空指针里面造成非法访问内存,导致程序崩溃。

  1. //正确程序
  2. void GetMemory(char **p)
  3. {
  4. *p = (char *)malloc(100);
  5. }
  6. void Test(void)
  7. {
  8. char *str = NULL;
  9. GetMemory(&str);
  10. strcpy(str, "hello world");
  11. printf(str);
  12. free(str);
  13. str = NULL;
  14. }

题目二:

  1. #define _CRT_SECURE_NO_WARNINGS 1
  2. #include <stdio.h>
  3. char* GetMemory(void)
  4. {
  5. char p[] = "hello world";
  6. return p;
  7. }
  8. void Test(void)
  9. {
  10. char* str = NULL;
  11. str = GetMemory();
  12. printf(str);
  13. }
  14. int main()
  15. {
  16. Test();
  17. return 0;
  18. }

 程序运行:

解析:

GetMemory函数将"hello world"首字母地址传给str,但是当GetMemory函数函数调用完后,"hello world"被销毁,str地址对"hello world"没有了访问权限,因此str为野指针

题目三:

  1. #define _CRT_SECURE_NO_WARNINGS 1
  2. #include <stdio.h>
  3. void GetMemory(char** p, int num)
  4. {
  5. *p = (char*)malloc(num);
  6. }
  7. void Test(void)
  8. {
  9. char* str = NULL;
  10. GetMemory(&str, 100);
  11. strcpy(str, "hello");
  12. printf(str);
  13. }
  14. int main()
  15. {
  16. Test();
  17. return 0;
  18. }

 程序运行:

 

解析:

 没有free,忘记释放。

题目四:

  1. #define _CRT_SECURE_NO_WARNINGS 1
  2. #include <stdio.h>
  3. #include <string.h>
  4. void Test(void)
  5. {
  6. char* str = (char*)malloc(100);
  7. strcpy(str, "hello");
  8. free(str);
  9. if (str != NULL)
  10. {
  11. strcpy(str, "world");
  12. printf(str);
  13. }
  14. }
  15. int main()
  16. {
  17. Test();
  18. return 0;
  19. }

 程序运行:

 解析:

free后将"world"拷贝到str里面是非法占用内存。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/40301
推荐阅读
相关标签
  

闽ICP备14008679号