Home > Software engineering >  C language Segmentation fault (core dumped) while coding strings
C language Segmentation fault (core dumped) while coding strings

Time:11-28

First i'm gonna apologize for my english as it's kinda meh and also it's my first time asking programming questions online so sorry if I make it unclear So, my problem is that I need a code that puts space before every capital letter in a string Example: AaaBbbCcC= Aaa Bbb Cc C However, I encountered the error Error Segmentation fault (core dumped) while doing so.

//this function takes a string from int main at the end of the code
void function(char s[]){    
    int stringsize=0;
    int a;
    while(s[stringsize]!='\0'){
        stringsize  ;
    }
    //I made this while to find the size of the string given
    stringsize  ;
    a=stringsize;
    //I used 'a' to have two variables to store this data
    //here I made a for to do the hard work and add a space before every capital letter, it simply sends everyone one house ahead and then put a space where it found the capital letter
    for(int i=0; s[i]!='\0'; i  ){
        if(s[i]>='A'&&s[i]<='Z'){
            while(a>i){
            a--;
            s[a 1]=s[a];
            }
           s[a]=' ';
         //the code works perfectly until here, it do its purpose, but since the while reduces the value of 'a' to the first capital letter it only works once, so here is the reason why I made two variables at the beginning, it adds 1 to stringsize (since the string grew one house) and gives the variable 'a' the new value to keep the for going. However, when I add this two lines of code the error Segmentation fault (core dumped) appears
           stringsize  ;
           a=stringsize;
            }
  
}

}
int main()
{
    char s[TAM];
//TAM is equal to 500 btw, I made a define just didn't put it here
    scanf("9[^\n]s", s);
    function(s);
    printf("%s", s);
    return 0;
}

Hope I made it clear enough, as I said i'm not a native english speaker and I'm a beginner at programing

CodePudding user response:

The problem is that when it inserts a space, it does not skip past the capital letter it just found, but instead keeps moving it and inserting spaces indefinitely. You can fix it by incrementing i after inserting a space:

#include <stdio.h>

#define TAM 500

void function(char s[])
{
    int stringsize=0;
    int a;

    while (s[stringsize] != '\0') {
        stringsize  ;
    }

    stringsize  ;
    a=stringsize;
    for (int i=0; s[i]!='\0'; i  ) {
        if (s[i] >= 'A' && s[i] <= 'Z') {
            while (a > i) {
                a--;
                s[a 1] = s[a];
            }
            s[a]=' ';
            stringsize  ;
            a=stringsize;
            i  ;    // add this line
        }
    }
}

int main(void)
{
    char s[TAM];
    scanf("9[^\n]s", s);
    function(s);
    printf("%s\n", s);
    return 0;
}
  • Related