char数组中不需要的文本

时间:2018-03-31 18:41:40

标签: c memory-leaks c-strings

我正在尝试"硬编码" C中的一个非常小的JSON解析器用于一个小项目,我遇到两个主要问题: 字符串输出包含一些来自无处的不需要的文本(实际上它是来自getaddrinfo()手册页的描述,我不知道它是如何到达那里的)。这是我得到的输出:

    3484.  The default is:
#
#precedence  ::1/128       50
#precedence  ::/0          40
#precedence  2002::/16     30
#precedence ::/96          20
#precedence ::ffff:0:0/96  10
#
#    For sites which prefer IPv4 connections change the last line to
#
#precedence ::ffff:0:0/96  100

#
# scopev4  <mask>  <value>
#    Add another rule to the RFC 6724 scope table for IPv4 addresses.
#    By default the scope IDs described in section 3.2 in RFC 6724 are
#    used.  Changing these defaults should hardly ever be necessary.
#    The defaults are equivalent to:
#
#scopev4 ::ffff:169.254.0.0/112  2
#scopev4 ::ffff:127.0.0.0/104    2
#scopev4 ::ffff:0.0.0.0/96       14
{id_src:103,accel_x:101,accel_y:114,accel_z:116,temp:101} <-- This is the only
wanted section !

我得到的第二个问题是,当我尝试将两个结构解析为json时,json有点附加两个结构:

 ... The usual unwanted data before
{id_src:103,accel_x:101,accel_y:114,accel_z:116,temp:101}{$­ûrc:1id_src:103,accel_x:101,accel_y:114,accel_z:116,temp:101}

我尝试减少分配的空间,结果在free()上出现错误,因为分配的char数组已经改变了它的大小。这也是一个我不太了解的奇怪行为。

以下是代码:

... some code here
char* jsonData = malloc(1048*sizeof(char));
    strcat(jsonData,"{");
    char* champsTab[] = {"id_src","accel_x","accel_y","accel_z","temp"};
    char* buff=malloc(1024*sizeof(char));
    for(i=0;i<5;i++) {
        strcat(buff,champsTab[i]);
        char* data=malloc(4*sizeof(char));
        switch(i) {
            case 0:
                sprintf(data,":%d,",capteurs->id_src);
                strcat(buff,data);
                break;
            case 1:
                sprintf(data,":%d,",capteurs->accel_x);
                strcat(buff,data);
                break;
            case 2:
                sprintf(data,":%d,",capteurs->accel_y);
                strcat(buff,data);
                break;
            case 3:
                sprintf(data,":%d,",capteurs->accel_z);
                strcat(buff,data);
                break;
            case 4:
                sprintf(data,":%d",capteurs->temp);
                strcat(buff,data);
                break;

        }
        free(data);

    }
    strcat(jsonData,buff);
    strcat(jsonData,"}");

    printf("%s\n",jsonData);
    free(jsonData);
    free(buff);

    return 0;
}

1 个答案:

答案 0 :(得分:1)

问题很可能是这两行:

char* jsonData = malloc(1048*sizeof(char));
strcat(jsonData,"{");

当您使用malloc分配内存时,它将是未初始化的。内容将不确定并且看似随机。因此,strcat查找结尾的字符串终结符很可能不是内存中的第一个元素。它可能根本就不在分配的内存中。

这是一个简单的解决方案:使用strcpy代替strcat

strcpy(jsonData,"{");

您稍后会遇到与buff相同的问题。