ccharc-stringsfunction-definitionstrncpy

Buffer overflow? strncat() in C


I'm very new to C, and I want to make a simple program that gets an index of a string from the value, and once it has the index, it removes it from a string. It's causing a buffer overflow error? Pretty sure it's from strcat from searching online but I'm not sure. Any help is appreciated! Also please don't use * in your answer, because I don't know how they work, I will learn very soon. (if its required for your answer, explain how you use it in the code please)

heres the code:

#include <string.h>

int findIndex(char string[], char substr) {
    for (int index = 0; index < strlen(string); index++) {
        if (string[index] == substr) {
            return index;
        }
    }
    return -1;
}

int main(void) {
    char howAreYou[9] = "howAreYou";
    char newString[9];

    int index = findIndex(howAreYou, 'o');
    
    for (int i = 0; i < 8; i++) {
        if (i != index) {
            strncat(newString, &howAreYou[i], 1);
        }
    }

    printf("new string: %s", newString);
  return 0;
}

Solution

  • Use char howAreYou[] = "howAreYou"; to allow for a terminating zero.
    Use char newString[sizeof howAreYou] = ""; to have the correct size for the array and initialize the array so it is empty before concatenation.

    #include <stdio.h>
    #include <string.h>
    
    int findIndex(char string[], char substr) {
        for (int index = 0; string[index]; index++) {
            if (string[index] == substr) {
                return index;
            }
        }
        return -1;
    }
    
    int main(void) {
        char howAreYou[] = "howAreYou";
        char newString[sizeof howAreYou] = "";
    
        int index = findIndex(howAreYou, 'o');
    
        for (int i = 0; i < sizeof howAreYou; i++) {
            if (i != index) {
                strncat(newString, &howAreYou[i], 1);
            }
        }
    
        printf("new string: %s\n", newString);
      return 0;
    }