On my school assignment i have to find a string with a brute force algorithm.
If the length is, for example , 3 these are all the possible combinations:
a
b
c
aa
ba
ca
ab
bb
cb
ac
bc
cc
aaa
baa
caa
aba
bba
cba
aca
bca
cca
aab
bab
cab
abb
bbb
cbb
acb
bcb
ccb
aac
bac
cac
abc
bbc
cbc
acc
bcc
ccc
I having problems in strcat.
here is the code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
# define PASS_SIZE 3
char letters[] = "abc";
char test[] = "acb";
int count = 0;
int nbletters = sizeof(letters)-1;
int bruteForce(int size);
int main() {
int i = 0;
int notFound = 1;
for (i = 1; i <= PASS_SIZE && notFound == 1; i++){
notFound = bruteForce(i);
};
printf("Count: %d\n",count);
return -1;
}
int bruteForce(int size){
int i;
int entry[size];
char pass[50];
char *temp;
for(i=0 ; i<size ; i++){
entry[i] = 0;
}
do {
for(i=0 ; i<size ; i++){
temp = letters[entry[i]];
printf("%c", temp);
strcat(pass,temp); /*Getting error here*/
}
count++;
printf("\n");
/*Compare pass with test*/
if (strcmp (pass,test) == 0){
return 0;
};
for(i=0 ; i<size && ++entry[i] == nbletters; i++){
entry[i] = 0;
}
} while(i<size);
return 1;
}
Probably the brute force algorithm is not the best one.
Why isn’t strcat working and I’m getting segmentation foult?
You are declaring your
passvariable but you are not initializing it. When you concatinate onto its end, you’re assuming initially its end is its start, but you need to make that be the case.More importantly, take a look at your
tempvariable. You’ve declared it to be achar *, but you’ve initialized it to be achar(instead of pointing to a char), and then instrcat()you treat it like a pointer again — but it’s not pointing anywhere valid (causing your crash).