Search code examples
cpointersfgetsmemset

memset() after while(fgets)


My program is supposed to read from stdin and hand over the input to the system - in case the input does not equal "exit". That works perfectly unless the second input is longer than the first. For example if the first input is "hello" and the second is "hellohello", the input gets split up into "hello" and "ello". I guess the problem is that the buffer s is not properly cleared while looping. Therefore I used memset() but unfortunately I did not get the results I was looking for.

Can anyone see the mistake?

Thanks a lot!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 1024

int main(){
char *s = (char *)malloc(MAX);
char *temp = NULL;
while(fgets(s, (sizeof(s)-1), stdin)!= NULL){

    temp = s+(strlen(s)-1);
    *temp = '\0';

    if (strcmp(s,"exit")==0){
         break;
    } else {
        system(s);
    }

    memset(s, 0, MAX);
}
free(s);
return 0;
}

Solution

  • The incorrect thing here is (sizeof(s)-1). This will not return size of allocated buffer, instead return size of (char*). You size of buffer is MAX. memset() really doesn't do anything with this, so remove it. an you do not need to do that -1, fgets() will always automatically attach zero terminator in the end of string, even if buffer filled up. Also these two lines

    temp = s+(strlen(s)-1);
    *temp = '\0';
    

    are not needed, because
    "fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte (aq\0aq) is stored after the last character in the buffer."
    (from "man fgets", google for it)