This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

为什么malloc只能分配10个字节内存空间?急切需要解答。



Sys/bios下如下任务函数

Void test()

         char  ip[]="192.168.2.15";

         char  gate[]="192.168.2.1";

          char ziwang ="255.255.255.0";

         char *ipdata =null;

         char *gatedata =null;

         char *ziwangdata =null;

          ipdata = (char *)malloc(sizeof(char)*12);

          gatedata = (char *)malloc(sizeof(char)*11);

          ziwangdata =(char*)malloc(sizeof(char)*13);

           strncpy(ipdata,ip,12);

           strncpy(gatedata,gate,11);

           strncpy(ziwangdata,ziwang,13);

通过查看ipdata的值不是192.168.2.15,而是192.168.2.

gatedata的值不是192.168.2.1,而是192.168.2.

ziwangdata的值不是255.255.255.0, 而是255.255.25,为什么

  • 使用 strncpy指定copy目的地址,即使申请的memory长度不够,也会copy指定长度的字符,所以与malloc分配的buf长度无关。建议你查看起始地址开始的memory宏存放的字符check copy之后目的地址存储的数据。

  • 为什么我将程序改成如下,输出结果不对,是malloc问题还是什么问题

    void test()

    {

         char ip [] = "192.168.2.15";

         char gate[] = "192.168.2.1";

         char ziwang[] = "255.255.255.0";

         char *ipdata = NULL;

         char *gatedata = NULL;

        char *ziwangdata = NULL;

        ipdata = (char *)malloc(sizeof(char));

       gatedata = (char *)malloc(sizeof(char));

       ziwangdata = (char *)malloc(sizeof(char));

      strncpy(ipdata,ip,12);

      strncpy(gatedata,gate,11);

      strncpy(ziwangdata,ziwang,13);

    }

    输出结果:ipdata依旧是192.168.2. gatedata依旧是192.168.2 ziwangdata依旧是255.255.25

    为什么不是ipdata 为1,gatedata为1,ziwangdata为1