sprintf()分段错误

时间:2013-08-17 11:45:55

标签: c segmentation-fault printf

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

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);

2 个答案:

答案 0 :(得分:6)

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

sprintf()的调用不是这种情况,因为只传递"%s",并且传入整数(需要"%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");

答案 1 :(得分:3)

101更改为"10""1",因为sprintf的相应转化说明符为%s,需要字符串。

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