Re: Wrong output - eliminate spaces in sentence.



spibou@xxxxxxxxx wrote:
CBFalconer wrote:

.... snip ...

Try this:

#include<stdio.h>

int main(void)
{
char t[]=" a b c d ";
char *source, *dest;

source = dest = t;
printf("input \"%s\"\n",t); /* note quotes to delimit blanks */

do {
while (' ' == *source) source++;
*dest++ = *source++;
} while (*source);
*dest = *source;

printf("output \"%s\"\n",t);
return 0;
}

I'm not sure if the code above is meant to test the opening
poster's dilligence but I think that the mistake may be too
subtle for a beginner and it won't necessarily be revealed by
testing the programme either so I'll spill (some of) the beans.
Scroll below for a hint.

What happens if after the line
while (' ' == *source) source++;
source points to the terminating byte ? Then source may boldly
go where no pointer has gone before !

You are right. I belatedly noticed it earlier, and prepared the
following for posting when my previous answer showed up.

#include <stdio.h>

int main(int argc, char* *argv)
{
char *source, *dest;

if (2 <= argc) {
source = dest = argv[1];
printf("input \"%s\"\n", argv[1]);

do {
while (' ' == *source) source++;
*dest++ = *source++; /* 13 */
} while (*source); /* 14 */
*dest = *source; /* 15 */

printf("output \"%s\"\n", argv[1]);
}
return 0;
}

This has an evil bug in it. If, in line 13, *source is '\0' and
that is the last valid location in argv[1], then line 14 is
dereferencing past the last location, and UB is present. I see
no simple way of preventing that without tortuous tests. Yet I
have been unable to trigger the bug with the above code!!

Am I missing something? Run with:

prog " a b c d " whatever

and vary the count of final blanks in argv[1].

--
Chuck F (cbfalconer@xxxxxxxxx) (cbfalconer@xxxxxxxxxxxxx)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE maineline address!

.



Relevant Pages