简体   繁体   中英

Segmentation fault (core dumped) allocating memory?

Im getting the error "Segmentation fault (core dumped)" when I run this program. I am new to c programming so its probably something stupid but i cant figure it out.

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

void swap(char *x, char *y){
    char temp = *x;
    *x=*y;
    *y=temp;
}

char** getPermutations(char *string){
    int length = strlen(string);
    int startIndex = 0;
    int endIndex = length - 1;

    if(startIndex == endIndex){
            printf("%s\n", string);
    }else{
            for(int j = startIndex; j<=endIndex; j++){
                    swap((string + startIndex),(string + j));
                    getPermutations(string);
                    swap((string+startIndex),(string+j));
            }  
    }    
}

int main(int argc, char *argv[]){
     if(argc>2){
            printf("\nToo Many arguments\n");
            exit(0);
    }else{
            printf("%s",argv[1]);
            char * str = malloc(strlen(argv[1]) + 1);
            strcpy(str,argv[1]);
            getPermutations(str);
    }
}

Your issue is that getPermutations calls itself endlessly. You need to pass something extra to it so it can know when to stop. As is, it just calls itself over and over until you have a stack overflow.

Also, you have getPermutations setup to return a char** , but then you never return anything. So that's odd too.

My suggestions:

  1. Change the return type of the function to void since it does not return anything.

  2. Change the name of the function to printPermutations since it just prints the permutations.

  3. Provide a way to end the recursion. Pass startIndex as an argument.

  4. Pass the length of the string so you don't compute it every time the function is called recursively.

  5. Change the comparison operator to >= to account for zero length strings.


void printPermutations(char *string, int startIndex, int length){
   int endIndex = length - 1;

   if(startIndex >= endIndex){
      printf("%s\n", string);
   }else{
      for(int j = startIndex; j<=endIndex; j++){
         swap((string + startIndex),(string + j));
         printPermutations(string, startIndex+1, length);
         swap((string+startIndex),(string+j));
      }  
   }    
}

and call it with:

printPermutations(str, 0, strlen(str));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM