0

buffeV is the problem here. When I strcat it is overwritten instead of appended.

char temper[12];char buffeV[12];char buffe[2];
if(version<10)
{
    sprintf(temper,"/0%d",version);
    strcpy(buffeV, temper);
}
if(version>=10)
{
    sprintf(temper,"/%d",version);
    strcpy(buffeV, temper);
}      
printf(" BUFFEV: %s ",buffeV);  
if(fileCount<10)
{
    sprintf(buffe,"0%d",fileCount);
    sprintf(temper,"/0%d/0000",fileCount);
    strcat(buffeV,temper);
}
if(fileCount>=10)
{
    sprintf(buffe,"%d",fileCount);
    sprintf(temper,"/%d/0000",fileCount);
    strcat(buffeV,temper);
}
printf(" BUFFEV: %s ",buffeV);

The printf's show that buffeV is /03 then /03/0000 when it is supposed to be /03/03/0000 They both aren't always the same value by the way, this is why it is separated. I've messed around with it quite a bit and cannot get a different outcome. I've also tried specifically declaring where the '\0' is to see if that would fix the problem but still no success. What is wrong with this code? Thanks

NOTE: version and fileCount are both ints declared elsewhere. But they are not the issue, the code was actually working fine until I realized I needed to check for fileCount being above 10 which is when I had to add the strcat when I was originally only using a sprintf

  • Please make a minimal compilable example. The `sprintf(buffe, ...)` calls mean you either have made a typo or omitted a variable declaration. – nobody May 09 '14 at 16:49
  • There you go, sorry I wasn't paying any attention to that variable. – user3602216 May 09 '14 at 16:52
  • `buffe[2]` is also too small. It needs to be at least 3 elements. Currently you are overflowing it and corrupting whatever variable is adjacent on the stack. – nobody May 09 '14 at 16:52
  • 2
    I think this is too complicated. Why not `buffeV[100];` and `sprintf("/%02d/%02d/0000", version, fileCount);` to replace the entire code snippet. – mshildt May 09 '14 at 16:54
  • Does the %02d mean that it will be 2 bytes every time? I didn't know of this... That's useful – user3602216 May 09 '14 at 16:56
  • Ah yes perfect all I had to do is increase buffe! It was overflowing as you said – user3602216 May 09 '14 at 16:58

2 Answers2

1

An easier way to go about this would be to let sprintf do all of the work for you:

buffeV[100];
sprintf(buffeV, "/%02d/%02d/0000", version, fileCount);

This will 0 pad any single digit values automatically. Which is what I think your code is trying to do.

Or a safer version:

buffeV[100];
snprintf(buffeV, 100, "/%02d/%02d/0000", version, fileCount);
mshildt
  • 8,782
  • 3
  • 34
  • 41
0

buffe[2] is too small. It needs to be at least 3 elements. The sprintf calls that populate it are overflowing into the adjacent variable on the stack (buffeV). buffe's terminating NUL ends up at buffeV[0], so the subsequent strcat(buffeV, ...) call sees a zero-length string in buffeV.

nobody
  • 19,814
  • 17
  • 56
  • 77