• 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");             "str 指针没有任何变化(值传递),还是指向NULL,没有内存,对NULL的空间进行操作,编译器会报段错误"
    10 printf(str); 
    11 } 
    12 请问运行Test函数会有什么样的结果?简述原因 .
    13 
    14 char *GetMemory(void)            
    15 { 
    16 char p[] = "hello world";                 "栈上的内存,程序结束内存就析构"17 return p; 
    18 } 
    19 void Test(void)                         
    20 {                                        "只有地址,没有内存,输出时乱码,看编译器的处理(有的编译器会报段错误)"
    21 char *str = NULL; 
    22 str = GetMemory(); 
    23 printf(str); 
    24 } 
    25 请问运行Test函数会有什么样的结果?简述原因 
    26 
    27 void GetMemory(char **p, int num) 
    28 { 
    29 *p = (char *)malloc(num); 
    30 } 
    31 void Test(void) 
    32 { 
    33 char *str = NULL; 
    34 GetMemory(&str, 100);                     "正常输出,但是内存没有释放,内存泄漏"35 strcpy(str, "hello"); 
    36 printf(str); 
    37 } 
    38 请问运行Test函数会有什么样的结果?简述原因 
    39 
    40 void Test(void) 
    41 { 
    42 char *str = (char *) malloc(100); 
    43 strcpy(str, “hello”); 
    44 free(str); 
    45 if(str != NULL) 
    46 {                                         "只有地址,没有内存,但是由于在同一个函数中,上一个地址中的内存可能还没有被其他程序占用,"
    47                                           " 所以拷贝时不会出段错误,而且正常打印,但是程序结束时会报段错误"
    48 strcpy(str, “world”); 
    49 printf(str); 
    50 } 
    51 } 
    52 请问运行Test函数会有什么样的结果?简述原因,应如何避免。 
  • 相关阅读:
    青城的另一个一夜/情
    SystemProperties.get/set property_get/set
    锁——Java同步的基本思想
    CMUSphinx Learn
    猜数字
    我的音乐我的电影
    动态规划_钢条切割问题
    directdraw显示yuv420(YV12)
    Redis 命令参考
    HDU 3078 LCA转RMQ
  • 原文地址:https://www.cnblogs.com/yyx1-1/p/5785579.html
Copyright © 2020-2023  润新知