0

我的程序中有分段错误。这是我的代码

char buffer[5000]="";
memset(buffer,0,sizeof(buffer));
sprintf(buffer,"<?xml version=\"1.0\" encoding=\"utf-8\"?>\
                        <soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:log=\"http://wsdlclass.wsdlcreat.sims.triesten.com\">\
                        <soap:Header>\
                        </soap:Header>\
                        <soap:Body>\
                        <log:saveMessBillingDetails>\
                        <log:userId>%s</log:userId>\
                        <log:billNo>%s</log:billNo>\
            <log:billingAmount>%s</log:billingAmount>\
            <log:billingDate>%s</log:billingDate>\
            <log:messId>%s</log:messId>\
            <log:itemId>%s</log:itemId>\
            <log:ipAddress>%s</log:ipAddress>\
            <log:schoolId>%s</log:schoolId>\
                        </log:saveMessBillingDetails>\
                        </soap:Body>\
            </soap:Envelope>",
  "00007", "152555", "42.00", "17-08-2013", 10, "CHKK", "10.10.1.164", 1);
4

2 回答 2

6

使用*printf*()函数系列时,您需要注意转换说明符的数量类型与格式“字符串”的参数相匹配。

在您对 的调用中并非如此sprintf(),因为只有"%s"where as 也传入了整数(需要"%d")。但是参数的数量是正确的。

更新:

您的代码的正确和安全版本可能是:

char buffer[5000]="";
int printed = snprintf(buffer, sizeof(buffer), "<?xml version=\"1.0\" encoding=\"utf-8\"?>\
  <soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:log=\"http://wsdlclass.wsdlcreat.sims.triesten.com\">\
  <soap:Header>\
  </soap:Header>\
  <soap:Body>\
  <log:saveMessBillingDetails>\
  <log:userId>%s</log:userId>\
  <log:billNo>%s</log:billNo>\
  <log:billingAmount>%s</log:billingAmount>\
  <log:billingDate>%s</log:billingDate>\
  <log:messId>%d</log:messId>\
  <log:itemId>%s</log:itemId>\
  <log:ipAddress>%s</log:ipAddress>\
  <log:schoolId>%d</log:schoolId>\
  </log:saveMessBillingDetails>\
  </soap:Body>\
  </soap:Envelope>",
  "00007", "152555", "42.00", "17-08-2013", 10, "CHKK", "10.10.1.164", 1);

  if (printed >= sizeof(buffer))
    fprintf(stderr, "The target buffer was to small.\n");
于 2013-08-17T11:48:47.620 回答
3

更改10and 1to"10""1"since 对应的转换说明符sprintf%s期望字符串。

或者您可以将相应的说明符从 更改%s%d

于 2013-08-17T11:49:31.397 回答