zoukankan      html  css  js  c++  java
  • 一道华为笔试题 ,内存相关

    下面一段程序,请说明输出结果:

    int _tmain(int argc, _TCHAR* argv[])
    {
      
    int *p1,*p2,value;
      p1
    =(int*)0x500;
      p2
    =(int*)0x518;
      value
    =p2-p1;
      printf(
    "%d\n", value);
     
    return 0;
    }


     结果为6.


    (0x518-0x500)/sizeof(int) =6

    0x0018/4=6

    void GetMemory(char *p)
    {
    p=(char*)malloc(100);
    }

    void Test(void)
    {
    char *str = NULL;
    GetMemory(str);
    strcpy(str,"helloworld");
    printf(str);
    }
    请问运行Test函数会有什么样的结果?
    答:程序崩溃。因为GetMemory并不能传递动态内存,Test函数中的str一直都是NULL。strcpy(str,"helloworld");将使程序崩溃。

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

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

    #include   <iostream.h>  
       
      class   A  
      {  
      unsigned   char   i;  
      virtual   f()   {};  
      };  
       
      class   B   :   public   A  
      {  
      };  
       
      class   C   :   virtual   public   A  
      {  
      };  
       
      class   D   :   public   B,   public   C  
      {  
      };  
       
      void   main()  
      {  
      cout   <<   "A:   "   <<   sizeof(A)   <<   endl;  
      cout   <<   "B:   "   <<   sizeof(B)   <<   endl;  
      cout   <<   "C:   "   <<   sizeof(C)   <<   endl;  
      cout   <<   "D:   "   <<   sizeof(D)   <<   endl;  
      }  
      结果为  
      A:   8  
      B:   8  
      C:   12  
      D:   20  
       
      A:1   char+3bit(补位)=4bit+1   ptr=8bit  
      B:sizeof(B)=0+sizeof(A)=8bit  
      C:sizeof(A)+1   ptr=12bit  
      D:sizeof(B)+sizeof(C)=20bit    

  • 相关阅读:
    day 05 讲解java三大特性
    day 02 运算符
    石大 6-9 待提交
    poj分类
    NLog使用总结
    VS 2010下单元测试
    MQTT----物联网常用的消息队列协议
    使用jfreechart生成柱状图、折线图、和饼状图
    JavaBean持久化
    使用maven搭建springMVC开发环境
  • 原文地址:https://www.cnblogs.com/likwo/p/1693590.html
Copyright © 2011-2022 走看看