Thread: How to prevent array overflow

  1. #1
    Registered User
    Join Date
    Oct 2020
    Posts
    69

    How to prevent array overflow

    I did the task:
    Implement a function that receives a C-styled string (s) and an array of characters (buff) together with its capacity and concatenates into buff all the words from s which are palindromes (we consider a word to be a palindrome if read from left to right is the same as being read from right to left;
    i.e. "hannah" is such an example).
    Avoid overflowing the array.
    A word is a sequence of non-whitespace chars separated by at least one whitespace char (the first and the last word might miss the leading or trailing whitespaces).

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <ctype.h>
    #include <string.h>
    unsigned checkWord(char word[])
    {
        for(int i = 0; i <= strlen(word); i++)
        {
            if(isspace(word[i]))
                return 0;
        }
        return 1;
    }
    unsigned checkPalindrome(char str[])
    {
        int l = 0;
        int h = strlen(str) - 1;
        while (h > l)
        {
            if (str[l++] != str[h--])
            {
                return 0;
            }
        }
        return 1;
    }
    void concatenatePalindromes(char s[], char buff[], int cap)
    {
        cap = 0;
        char* word = strtok(s, " ");
        while(word != NULL)
        {
            if(checkWord(word) == 1 && checkPalindrome(word) == 1)
            {
                strcat(buff, word);
            }
            word = strtok(NULL, " ");
        }
        cap = '\0';
        printf("%s", buff);
    }
    int main()
    {
        char s[] = "ana john michael hannah ana stacy";
        char buff[] = ""; //anahannahana
        concatenatePalindromes(s, buff, 40);
        return 0;
    }

    The code is working as intended, but I used a random value for the size of buff (40), because I have no idea how to avoid overflowing the array. How do I keep track of the size and choose a fitting size? What are some ways to avoid overflowing the array?

  2. #2
    Registered User
    Join Date
    Dec 2017
    Posts
    1,626
    The code is working as intended
    It might seem to be working, but it's not. There are a lot of mistakes in your code.

    The worst thing is that you have given buff a size of 1 char. Remember that if you don't specify a size in the square brackets then it takes its size from the initializing string. The string "" only has the terminating '\0' character, and therefore a size of 1. You can't pretend that it's actually 40 if it's really only 1.

    You then treat cap in a really strange way. Firstly you erase the value of 40 that it initially had, setting it to 0. Then you do nothing with it except set it to 0 again (using '\0') before the function returns.

    What you need to do is to properly size buff, pass in that size, and then use cap to ensure you don't write beyond that size.

    Also, checkWord doesn't do anything useful since the strtok function will ensure that there are no spaces in the word.

    Little things:

    Are you sure you're not supposed to add a space between the words that you append to buff? (Depends on the instructions.)

    Don't print buff inside concatenatePalindromes. Print it in main after concatenatePalindromes returns.

    There's no reason to use unsigned for boolean return values. Use int, or include <stdbool.h> and use bool.

    Don't test a bool value against 1 or 0 (or true or false). Just test it. I.e.:
    Code:
    // Don't do this:
    if (checkPalindrome(word) == 1)
    
    
    // Do this instead:
    if (checkPalindrome(word))
    Code:
    #include <stdio.h>
    #include <ctype.h>
    #include <string.h>
    #include <stdbool.h>
     
    bool checkPalindrome(const char *str)
    {
        int l = 0, h = (int)strlen(str) - 1;
        while (h > l)
            if (str[l++] != str[h--])
                return false;
        return true;
    }
     
    void concatenatePalindromes(char *s, char *buff, int cap)
    {
        buff[0] = '\0'; // ensure buff starts empty and zero-terminated
        char *word = strtok(s, " ");
        while (word)
        {
            if (checkPalindrome(word))
            {
                int len = strlen(word);
                if (len + 1 > cap) // +1 for '\0'
                {
                    printf("string overflow\n");
                    return;
                }
                cap -= len;
                strcat(buff, word);
            }
            word = strtok(NULL, " ");
        }
    }
     
    int main()
    {
        char s[] = "ana john michael hannah ana stacy";
        char buff[100]; //anahannahana
        concatenatePalindromes(s, buff, sizeof buff);
        printf("%s\n", buff);
        return 0;
    }
    Last edited by john.c; 01-03-2021 at 11:13 AM.
    A little inaccuracy saves tons of explanation. - H.H. Munro

  3. #3
    Registered User
    Join Date
    Oct 2020
    Posts
    69
    Thanks a lot! I copy-pasted the task so I don't think I should add a space. I'll keeps the little things in mind for future code

  4. #4
    Registered User
    Join Date
    Jan 2021
    Posts
    1

    Tips to avoid array overflowing

    Quote Originally Posted by rmmstn View Post

    The code is working as intended, but I used a random value for the size of buff (40), because I have no idea how to avoid overflowing the array. How do I keep track of the size and choose a fitting size? What are some ways to avoid overflowing the array?
    // Don't do this:
    if (checkPalindrome(word) == 1)


    // Do this instead:
    if (checkPalindrome(word))
    Last edited by Salem; 01-06-2021 at 12:15 AM. Reason: Removed spammy link, and the over long quote.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how to prevent stack-overflow?
    By albert3721 in forum C Programming
    Replies: 6
    Last Post: 12-10-2007, 06:51 PM
  2. Best way to prevent buffer-overflow
    By Siphon in forum C Programming
    Replies: 1
    Last Post: 01-01-2007, 11:53 AM
  3. array bounds overflow
    By BendingUnit in forum C Programming
    Replies: 3
    Last Post: 06-18-2006, 10:45 PM
  4. Array overflow
    By soulredemption in forum C Programming
    Replies: 2
    Last Post: 09-07-2005, 11:19 PM
  5. Array bounds overflow
    By athos in forum C++ Programming
    Replies: 3
    Last Post: 08-10-2004, 12:05 PM

Tags for this Thread