Search code examples
carraysmemset

Cleaning a static char array after use


I want my program to clean the static chars array for a new input I've tried with memset but it doesn't work or i'm doing it wrong. please some advice. Thanks in advance.

const char * password() {
     static int i = 0;
     static char pwd[STRING_LEN], c = '\0';
     static char return_buffer[255];

     memset(pwd, 0, sizeof pwd);     //<---
     memset(return_buffer, 0, sizeof return_buffer);     //<--

     printf("Password: ");
     while (i < STRING_LEN){
         pwd[i] = getch();
         c = pwd[i];
         if(c == 13) { break; }
         i++;
     }
     pwd[i] = '\0';

     snprintf(return_buffer, sizeof(return_buffer), "%s", pwd);
     printf("\n");
     return return_buffer;
}

Solution

  • Besides that there is no need to "clean" the arrays since you are overwriting their content with the result of getch() and a '\0' ... you never reset i.

    i is a static int that only will get initialized the first time, execution passes its point of definition. Also, there is no need for i and pwd to be static variables.