sprintf()分段错误

GoS*_*ash 0 c printf segmentation-fault

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

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);
Run Code Online (Sandbox Code Playgroud)

alk*_*alk 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");
Run Code Online (Sandbox Code Playgroud)