Error comparing two strings

2

I'm trying to compare two strings , so when I enter a name in my threaded list it can not be inserted if it already exists. I have already used the search_name function to display a searched name and to exclude, but now it is simply giving segmentation fault on the line that calls strcmp() . Here is the code for the functions related to the problem.

void insere_inicio(celula *nodo) {
    celula *teste;
    printf("\t Nome: ");
    ler_string(busca.nome, 30);
    teste = busca_nome( nodo);
    if (teste == NULL) {
        celula *info;
        info = malloc(sizeof (struct cel));
        strcpy(info->nome, busca.nome);
        printf("\t Rua: ");
        ler_string(info->rua, 40);
        printf("\t Cidade: ");
        ler_string(info->cidade, 20);
        printf("\t Estado: ");
        ler_string(info->estado, 2);
        printf("\t CEP: ");
        scanf("%lu", &info->cep);
        info -> prox = nodo -> prox;
        nodo -> prox = info;
    } else {
        printf("Esse nome já está cadastrado !!");
    }
    free(teste);
}

/*
 * função que faz a busca de um nome no programa
 * le o nome que está localizado na struct busca.nome
 * se encontra um nome igual retorna o ponteiro para o nome
 * caso não encontre retorna um ponteiro NULL
 */
celula *busca_nome(celula *inicio) {
    int flag = 0;
    celula *info;
    celula *anterior;
    do {
        if (flag == 0) {
            anterior = inicio;
            info = inicio -> prox;
            flag = 1;
        } else {
            anterior = info;
            info = info -> prox;
        }
        if (strcmp(busca.nome, info -> nome) == 0)
            return anterior;
    } while (info -> prox != NULL);

    return NULL;
}
    
asked by anonymous 05.12.2014 / 20:05

1 answer

3

The code is full of problems. I'll point out a few:

The main visible is memory corruption. The variables info and anterior were declared but memory was not allocated for them. When you tried to write something in them, you have memorized, possibly wrote on something important.

I also do not know where the busca variable came from. It does not exist in this scope. Does it exist in a larger scope? Even if this is not a good practice in most cases.

This if with flag does not make much sense to me, but it probably works.

And in the other function you try to free the memory of something that has never been allocated.

Tip: Whenever possible (almost always is) use malloc() and free() which frees it in the same function. To use them separately is to seek confusion. Even experienced programmers get lost when they do this.

Some other technical things are strange but without seeing the whole I'm not sure. The algorithm as a whole does not seem to make much sense.

    
05.12.2014 / 20:21