1
votes

When I run this code I get an error segmentation fault (core dumped). I see that the error lies in " printf("%c", first(s));", it seems that it is not the correct way to pass char/string to function? if not then what is the problem with my code?

#include <stdio.h>
char first(char *str);
char first(char *str){
    int L=0;
    int a[127]={0};
    for (int i=0; i<127; i++){
      a[i]=i+1;
    }
    while (str != '\0'){
      for(int d=1; d<127; d++){
        if(str[L]==(char)d){
            if (a[L]>0){
                a[L]=0;
                L++;
                break;
            }
            else if(a[L]==0){
                a[L]=-1;
                L++;
                break;
            }
            else{
                L++;
                break;
            }
        }
    }        
  }
  for(int i=0; i>127; i++){
      if(a[i]==0)
          return (char)(i+1);
  }
  return '\0';
}

int main()
{
  char s="blazqnqbla";
  printf("%c", first(s));

  return 0;
}
2
Wrong wording. The core dump is very probably not from your compiler, but when running the executable produced by compiling your source code. The bug is inside your program, not in the compiler. Read how to debug small programs - Basile Starynkevitch
Your character pointer is not declared properly. Change char s="blazqnqbla"; to char *s="blazqnqbla"; - Rishikesh Raje
'while (str!= '\0')' is also problematic. You can't compare a char* to a char - BlackJack
try compiling with warnings -Wall -Wextra -pedantic. - Paul Rooney

2 Answers

2
votes

Not sure what you are trying to do here, so cannot help with the algorithm.

To solve your core dump issue you need to do two things.

  1. Define the character pointer as

    char *s="blazqnqbla";  // you had defined it as char s="..."
    
  2. Change the while loop condition from while (str!= '\0') to

    while (str[L]!= '\0')
    

With these changes the program exits properly. There is still some algorithm problem with the function first. It is not giving any meaningful output.

1
votes

I don't know what are you aiming to achieve with this code but this has lot of mistakes.

Exclusively for your segmentation fault error you will have to change initialization of "s" like char *s="blazqnqbla"; or char s[]="blazqnqbla"; Since s is storing array of characters.

Also your code has infinite while loop please modify that like while (str[L] != '\0')