09-23-04 10:54 PM
In article <d3be1825.0409231206.5d120ed8@posting.google.com>,
jani@persian.com (Jani Yusef) wrote:
> When I compile and executethe code below I se ethis weidness in the
> output. For example,
> $ ./a.out 2 3
> puke
> puke
> üÿ¿Xüÿ¿Æ-
>
> Where are those weird characters coming from? This is on a Debian 3
> box but I see the same thing on Solaris, for what that's worth.
>
>
> #define MAXBUFFER 7
> int main(int argc, char *argv[]){
>
> char input[MAXBUFFER ];//create a character array to hold
> input from the
> user
> char output[MAXBUFFER ];//create a character array to hold
> output
> int depth=atoi(argv[2]);
> numberOfProcesses=atoi(argv[1]);
>
> read(0,input,MAXBUFFER );
read() doesn't always fill the buffer, and may even return an error. You
have to check the return value to determine whether there was an error, and
if not, how many characters it put into the buffer.
> sprintf(output,"%s",input);
You're using input as if it were a zero-terminated string, but read()
doen't zero-terminate it. You have to either add a zero byte after the
last byte read, or specify the string's length via the "*" format spec.
sprintf() will zero-terminate the data it writes into the output buffer, so
that buffer needs to be big enough for that extra byte. Likewise for the
input buffer if you decide to zero-terminate it.
[ Post a follow-up to this message ]
|