1

我正在编写一个作为标准输出打印的函数,就像普通的 printf 函数一样,但不采用 %d 或 %s 等指标,它需要 {i} 或 {s}。我遇到的问题是,当格式参数的字符串太长约 23 个字符时,我在调用 vfprintf 函数的行出现分段错误。

        int mr_asprintf(const char *format, ...)
        {
            int i;
            char *newFormat = calloc(1,sizeof(char));
            char integer[3] = "%d";
            char str[3] = "%s";
            char tmpStr[2];
            va_list args;
            newFormat[0] ='\0';
            tmpStr[1] = '\0';
            for(i=0;format[i]!='\0';i++) // convert to printf syntaxe
            {
                if(format[i]=='{' && format[i+2]=='}') //check if it's {x}
                {
                    switch(format[i+1]) 
                    {
                        case 'i':
                            strcat(newFormat,integer);
                            i += 2;
                            break;
                        case 's':
                            strcat(newFormat,str);
                            i += 2;
                            break;
                    }
                }
                else
                {
                    tmpStr[0] = format[i];
                    strcat(newFormat,tmpStr);
                }

            }
            va_start(args,format);
            int s = vfprintf(stdout,newFormat,args);
            va_end(args);
            free(newFormat);
            return s;
        }

测试示例:

    int main()
    {

        char *result = mr_asprintf("bce }edadacba{i}}aa}da{s}fe aeaee d{i}cefaa",55,"XXX",66);
        printf("%s\n",result);
        return 0;
    }
4

1 回答 1

1

您的字符串newFormat被分配为大小 1,并且您正在使用 strcat 附加到它 - 但 strcat 不会调整任何数组大小,因此newFormat很快就会开始踩踏未分配的内存。输出字符串的长度将始终 <= 输入字符串的长度,因此您可能应该分配一个该大小的字符串。

最后,虽然这不应该导致 vprintf 中的段错误,但它可能会在以后导致意外行为 -

for(i=0;format[i]!='\0';i++) // convert to printf syntaxe
{
    if(format[i]=='{' && format[i+2]=='}') //check if it's {x}

您检查当前位置是否是字符串的结尾,然后检查当前位置之后的两个字符是否有右括号,而不检查字符串是否在下一个空格结尾。这可能会导致在为您的数组分配的内存之外进行读取。将 if 语句替换为if(format[i]=='{' && (format[i+1]=='i' || format[i+1]=='s') && format[i+2]=='}')可以避免该问题。

于 2018-04-07T19:19:36.983 回答