Hi. I've posted here regarding this before, but I moved on and am coming back to it now since I am still having trouble figuring the string permutation using recursion issue.
The issue I am having is that somewhere before checkpoint 2 there is a segmentation fault. My program just keeps spitting out the same 2 permutations until until it gives the error message. I would love to understand why?
Code:
$ ./test.1 -o test.1.c | sort -u
chechpoit-1: ABCD
chechpoit-1: CBAD
checkpoint-2 ABCD
checkpoint-2 CBAD
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap(char *a, char *b){
char temp;
temp = *a;
*a = *b;
*b = temp;
}
void permute( char *str, int i, int n){
int j;
if (i == strlen(str))
printf("%s\n", str);
else{
for( j = i; j <= strlen(str); j++){
printf("chechpoit-1: %s\n", str);
fflush(0);
swap(str+i,str+n);
printf("checkpoint-2 %s\n", str);
permute(str, i, n);
printf("checkpoint-3 %s\n", str);
swap(str+i,str+n);}
}
}
int main(void){
char *ptr;
char string[] = "ABCD";
ptr = string;
permute(ptr,0,2);
return 0;}