View previous topic :: View next topic |
Author |
Message |
hmmpic
Joined: 09 Mar 2010 Posts: 314 Location: Denmark
|
sprintf(...) problem with null terminated string... |
Posted: Mon Mar 19, 2012 12:18 pm |
|
|
Have some problem with sprintf.
If running this in "Code::Bloch" GNU GCC i have what I expect. But CCS does something other.
CCS: 4129
PIC18F25K22
I have made this small test program. What i expect is after using sprintf(...) the Buff will be an empty string, it is not.
Buff is is same as from the beginning = strcpy(Buff,"Buff"); Look like if null terminated string something goes wrong.
Maybe i made something wrong?
Code: | //sprintf problem!
void TSprintf(){
char PNULL[10];
char Buff[10];
strcpy(PNULL,"PNULL");
strcpy(Buff,"Buff");
PNULL[0]=0x00; //now length is 0
sprintf(Buff,"%s",PNULL);//expect Buff is empty!
printf("Buff:%s\r\n",Buff);
} |
|
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Mon Mar 19, 2012 2:13 pm |
|
|
I got the same result as you. I tested it with vs. 4.130.
With CCS sprintf, it apparently checks if the source string is empty
and if so, it doesn't do anything to the output string. It doesn't write
a string terminator to the first byte of the output string. I tested it
in MSVC 6.0, and it does write it. So, there is a difference between
the two compilers.
If you own the compiler, you should email CCS support about this bug. |
|
|
hmmpic
Joined: 09 Mar 2010 Posts: 314 Location: Denmark
|
|
Posted: Mon Mar 19, 2012 2:36 pm |
|
|
Thanks, and the error is now reported to CCS. |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19498
|
|
Posted: Tue Mar 20, 2012 3:25 am |
|
|
A nicely spotted bug.
You can understand exactly 'why', but if CCS start to claim that this isn't a bug, point them at the sprintf definition in K&R, which specifically says "the output is written into the string s, terminated with '\0'". So the termination is required, and should always be generated, whatever the source data is doing.....
Best Wishes |
|
|
asmboy
Joined: 20 Nov 2007 Posts: 2128 Location: albany ny
|
|
Posted: Tue Mar 20, 2012 9:13 am |
|
|
The implications of this are a bit unsettling though.
There are quite a few downstream dependencies on sprintf()
in other supplied library files, but fortunately - it appears that the majority
involve calling it to load constant, non -null - data.
So, I wonder in what version , IE: when this CONCEPTUAL error first manifested
AND if the failure to spit out a terminator in the null target situation
-might be suspected elsewhere in the compiler, such as in the logic behind the string.h lib functions. ??? |
|
|
|