Search code examples
carraysprintfsegmentation-faultfault

C sprintf buffer sigsegv error


I'm having a problem with my program: I keep getting segmentation fault on a sprintf function and i can't get why,the buffer is large enough and i THINK to be passing the pointer correctly,i just can't figure out why it won't work.

Here's the code:

Calling:

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 code:

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;
         }
      //........
    }
}

I'm pretty sure that the problem is "dataBuff" since even if i use sprintf to try to store a normal constant string it gives me the same error. It's just...i can't figure out what i'm doing wrong. Thanks in advance.

EDIT:problem solved as function header:

int BuildCMD(enum CMD cmd,int *values,float Res,char dataBuff[100])

as sprintf call:

sprintf(&dataBuff,"0*;%d;%d;%d;%d;%d;%d;%.5f|\n",cmd,values[0],values[1],values[2],values[3],values[4],Res);

Solution

  • For BuildCMD() the parameter dataBuff is a pointer. But you have declared dataBuff as array of pointers! if you have char dataBuff[100]; then you can use BuildCMD(CALC,tmpData,0.f,dataBuff);