Search code examples
carraysstringstrcatstrncpy

adding string to character array at specific position giving buffer overflow in c programming


I am very new to c programming, and for a school assignment I need to write a programm that takes a string as input and add the letters “ay” to each word that starts with a consonant at the front of this word. It is hinted that this should be done with strncpy and strcat.

this is the code that I wrote:

    #include <stdio.h>
    #include <string.h>

    int main()
    {   
        char myString[50];
        char abc[26] = "bcdfghjklmnpqrstvwxyz";
        char strA[50];
        char strB[50];
        char strC[150];
        char ay[3] = "ay";
        printf("** Welcome to the Double Dutch game **\nPlease enter a string: ");
        scanf(" %[^\n]s", &myString);
        int i, j;
        for (i=0; myString[i]!='0'; i++) {
            for(j=0; abc[j]!='\0'; j++) {
                if(abc[j] == myString[i]){
                    if(myString[i-1] == ' '){
                        strncpy(strC, &myString[0], i);
                        strncpy(strB, &myString[i], 40);
                        strcat(strC, ay);
                        strcat(strC, strB);
                        myString[0] = '\0';
                        strcat(myString, strC);
                        strC[0] = '\0';
                        strB[0] = '\0';
                    }
                }
            }
        }
        printf("Result: %s", myString);
    }

When i run this code it keeps giving the error * Buffer overlow detected *: /home/a.out terminated. I cannot find the mistake that I made. Hopefully someone can help me. Thanks


Solution

  • Change this:

    scanf(" %[^\n]s", &myString);
    

    to this:

    scanf(" %[^\n]", myString);
    

    since %[^\n] conversion modifier is not a modifier for %s, they are independent. As a result, you can discard it.


    Tip: Add the size of your array - 1, to prevent a possible buffer overflow, like this: scanf(" %49[^\n]", myString);