Search code examples
ceeprom

Check if char array is not garbage? (valid chars)


I have a char array in which reads data from some EEPROM device, in hardware, and if there is no data in there, its value can be anything (garbage).

I would like to check if his value is not garbage and have some valid chars.

                       for(int k=address;k<address+MEM_MAX_LEN;k++)
                       {
                           charBuf[k-address]= EEPROM.read(k);
                           if(charBuf[k-address]=='*')
                         {
                              charBuf[k-address]='\0';
                              break;
                         }

When using strlen>1 I don't get the desired respond (obviously).

How can I check it?


Solution

  • You can never be sure, since garbage can look like valid text, but you can make reasonable guesses. Something like this, assuming that a valid string should be NUL-terminated and contain only printable characters:

    #include <ctype.h> // For isprint
    
    // ....
    
    int length = 0;
    while (length < MEM_MAX_LEN && charBuf[length] != '\0')
        ++length;
    
    if (length == 0) {
        printf("Empty string. Probably garbage!\n");
        return 0;
    }
    
    if (length == MEM_MAX_LEN) {
        printf("No NUL byte found. Probably garbage!\n");
        return 0;
    }
    
    for (int i = 0; i < length; ++i) {
        if (!isprint((unsigned char)charBuf[i])) {
            printf("Unprintable char (code %d) at position %d. Probably garbage!\n",
                   (unsigned char)charBuf[i], i);
            return 0;
        }
    }
    
    printf("String consists of %d printable characters. Probably not garbage!\n", length);
    return 1;