View previous topic :: View next topic |
Author |
Message |
Will Reeve
Joined: 30 Oct 2003 Posts: 209 Location: Norfolk, England
|
sprintf "bug" or my misunderstand of c? |
Posted: Thu Dec 22, 2005 4:11 am |
|
|
Basically dummy can be populated with a 4 character string terminated with \0. This works for 1,2,3, and 4 characters perfectly. However if I don't have any characters...for example:
char dummy[5];
char line1[17]
dummy[0] = '\0';
sprintf(line1,"%S",dummy);
this doesn't seem to do what I want it to do and null terminate the string, i.e. make line1[0] = '\0' but it doesn't do this. The line1 array still contains the original contents and isn't touched by the sprintf in this case.
However:
dummy[0] = 'A';
dummy[1] = '\0';
sprintf(line1,"%S",dummy);
correctly populates line1 with 'A' '\0'
I am wondering if this a C feature or a compiler "feature". I am using 3.241 |
|
|
Will Reeve
Joined: 30 Oct 2003 Posts: 209 Location: Norfolk, England
|
|
Posted: Thu Dec 22, 2005 4:33 am |
|
|
I am going to revise my question a little:
sprintf(line1,"");
or indeed:
sprintf(line1,"\0");
doesn't do what I hope which is
line1[0] = '\0';
Accoring to my understand of c The sprintf() function places output followed by the null byte, '\0'
If there isn't anything to place in the string should it still place \0 ? The CCS compiler doesn't (at least not my version) should it? |
|
|
Ttelmah Guest
|
|
Posted: Thu Dec 22, 2005 5:56 am |
|
|
Really it is just a case of trying to do something the function is not designed/guaranteed to handle. If you pull the Linux sprintf manual page (on the version I have at least), it makes the comment, that 'the results are undefined if an argument has zero size". This suggests that other compilers also exhibit this sort of behaviour.
So I'm afraid the Linux manual says it all. This is an 'undefined' state.
I'd actually suspect (it'd be worth looking at the listiing file generated), that the optimiser, is seeing that there is no argument, and is optimising the call out of existence.
Best Wishes |
|
|
Guest
|
|
Posted: Thu Dec 22, 2005 8:42 am |
|
|
I see what you are saying. I don't think it's an optimisation problem as the second "dummy" string array is created dynamically by other parts of the code. It's only when it's been loaded with '\0' as the first character that the sprintf problem happens! Took me a while to spot it :-) I will set a flag to cover the problem of "dummy" array being zero length.
I don't think the old way of making your own sprintf command and printf'ing to it will help as I suspect printf will also ignore an '\0' as the first byte. |
|
|
Ttelmah Guest
|
|
Posted: Thu Dec 22, 2005 9:59 am |
|
|
Yes.
Of course if the compiler allowed you to generate variable length argument lists for your own functions, it'd be a 'doddle', to just encapsulate the sprintf, into your own 'checked_sprintf' function that did this. This is one of the 'weaknesses' of the compiler... :-(
Best Wishes |
|
|
|