Question

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

Was it helpful?

Solution 2

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.

OTHER TIPS

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top