缓冲的字符串损坏

时间:2011-12-02 02:23:30

标签: c xml string buffer

我在C中制作XML格式化程序。它确实很顺利,但我之前的方法(每个字符的直接printf)不会为每一行打印适当数量的空格。因此,我每次都创建一个字符串缓冲区realloc来编辑它以打印一个新字符。 (我知道这不是最好的,但我不在乎。)新代码不会清除缓冲区或正确检测换行符。

void bufprint(char **line, char *poo) {
    /*SNIP old code without realloc*/
    *line=realloc(*line,strlen(*(line))+1+strlen(poo));
    strcpy(*line+strlen(*line),poo);
}

并且buf被声明为char *buf=malloc(1);。 bufprint被称为:bufprint(&buf,"<");

清除缓冲区代码:

    if (new) {
        new=False;
        int i;
        for (i=0; i < level; i++) {
            printf(" ");
        }
        printf("%s",buf);
        free(buf);
        buf=malloc(1);
        printf("\n");
        //printf("BUFFER CLEARED! --------------");
        //printf("New buffer: %s %d",buf,strlen(buf));
    }

示例输出:

<
 <root>
  <root><element num="1">
  This is element 1

 </element>
  </element><element num="2">
  This is element 2

   <subelement>
   <subelement>This is a sub-element

  </subelement>
  </subelement>Self-closing tag:

  <br />
 <br /></element>
</root>

1 个答案:

答案 0 :(得分:4)

malloc(1)调用将刚刚分配的字节清零。您必须自己执行此操作,否则新分配的内存可能包含一些随机非零字节。

buf = malloc(1);
buf[0] = '\0';

如果这不能解决您的问题,那么该错误可能位于您未向我们展示的其他地方。