【发布时间】:2013-06-09 13:35:03
【问题描述】:
我的程序有问题:我一直在 sprintf 函数上遇到分段错误,我不明白为什么,缓冲区足够大,我认为可以正确传递指针,我就是不能弄清楚为什么它不起作用。
代码如下:
调用:
char dataBuff[100];
//same error with char *dataBuff=malloc(sizeof(char)*100);
//those vars were declared before
int tmpData[5]={TID,i,JobList[i].Num1,JobList[i].Op,JobList[i].Num2};
//here's the function that return the sigsegv error
BuildCMD(CALC,tmpData,0.f,dataBuff);
BuildCMD 代码:
int BuildCMD(enum CMD cmd,int *values,float Res,char *dataBuff)
{
switch(cmd)
{//........
case CALC:
{
//this line cause the error,it's just a formatted parameters list
//note:same error with just
//sprintf(dataBuff,"abc");
spritf(dataBuff,"0*;%d;%d;%d;%d;%d;%d;%.5f|\n",cmd,values[0],values[1],values[2],values[3],values[4],Res);
break;
}
//........
}
}
我很确定问题是“dataBuff”,因为即使我使用 sprintf 尝试存储一个普通的常量字符串,它也会给我同样的错误。 这只是......我无法弄清楚我做错了什么。 提前致谢。
编辑:问题已解决 作为函数头:
int BuildCMD(enum CMD cmd,int *values,float Res,char dataBuff[100])
作为 sprintf 调用:
sprintf(&dataBuff,"0*;%d;%d;%d;%d;%d;%d;%.5f|\n",cmd,values[0],values[1],values[2],values[3],values[4],Res);
【问题讨论】:
-
您不必要地缩短了您认为存在问题的那一行。不要那样做——向我们展示你在实际代码中使用的真正的 sprintf 语句。
-
已编辑帖子,抱歉没有早点发布。
-
你没有复制代码,因为
spritf不是标题中的函数。 -
抱歉,老实说,我不明白为什么人们一直说这不是该死的真实代码,我刚刚删除了 switch 中的另一个案例。
-
.. 见上图感觉不是真正的代码。
标签: c arrays printf segmentation-fault fault