简体   繁体   中英

Error using strcat

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: abc 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 pass variable 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 temp variable. You've declared it to be a char * , but you've initialized it to be a char (instead of pointing to a char), and then in strcat() you treat it like a pointer again -- but it's not pointing anywhere valid (causing your crash).

strcat is expecting a null-terminated string, but char pass[50] hasn't been initialized. Set pass[0] = '\\0' to get a valid C string.

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