Search code examples
cstrncmp

strange behavior of strncmp


this code has a strange behavior in the "check_connected" procedure. The parameter is converted to char [30] before use the strncmp function, if not, the result is "stack overflow". The problem arises in the result of the compare of two strings, "Le solteria rige el corason.." --> this is the parameter "La solteria rige el corazon..." --> this is stored in the list The result is 0. I understand that the strncmp compare all the character of the strings and by common sense the result should not by zero.

#include <string.h>
#include <stdio.h>
#define LONGITUD_USUARIO 30
//estructuras de socorro
typedef struct nodo_list{
    char id_usuario[LONGITUD_USUARIO];
    struct nodo_list *siguiente;
} nodo;
//definiciones
#define TRUE 1
#define FALSE 0
//variables
nodo *headlist;
int size_var;
//declaracion de metodos
void initialize_list();
int add_connected(char *id_usuario);
int check_connected(char *id_usuario);
int disconnect(char *id_usuario);
int isEmpty();
int size();
//implementacion de metodos
/*
    Dado un id usuario lo incorpora al principio de la lista
*/
int add_connected(char *id_usuario){
    nodo nuevoNodo;
    strcpy(nuevoNodo.id_usuario, id_usuario);
    nuevoNodo.siguiente = headlist;
    headlist = &nuevoNodo;
    size_var++;
    return TRUE;
}
int check_connected(char *id_usuario){
    nodo *cursor = headlist;
    char id_user[LONGITUD_USUARIO];
    sprintf(id_user,"%s",id_usuario);
    printf(" ----> %d \n",strncmp(cursor->id_usuario, id_user,LONGITUD_USUARIO));
    if(!isEmpty()){
        while(cursor != NULL && (strncmp(cursor->id_usuario, id_user,LONGITUD_USUARIO) != 0)){
            printf(" ----> %d \n",strncmp(cursor->id_usuario, id_user,LONGITUD_USUARIO));
            cursor = cursor->siguiente;
        }}
    return cursor != NULL ;
}
int disconnect(char *id_usuario){
    nodo *cursor = headlist, *anterior = NULL;
    char id_user[LONGITUD_USUARIO];
    sprintf(id_user,"%s",id_usuario);
    if(!isEmpty()){
        while(cursor != NULL && strncmp(cursor->id_usuario, id_user, LONGITUD_USUARIO) != 0){
            anterior = cursor;
            cursor = cursor->siguiente;
        }
        if(anterior == NULL){ // es el primero
            headlist = cursor->siguiente;
            size_var--;
            return TRUE;
        }
        else
            if(cursor != NULL){
                anterior->siguiente = cursor->siguiente;
                size_var--;
                return TRUE;
            }
    }
    return FALSE;   
}
void initialize_list(){
    headlist = NULL;
    size_var = 0;
}
int size(){
    return size_var;
}
int isEmpty(){
    return size() == 0;
}
void tester_list(){
    initialize_list();
    printf("Inicializo\n");
    if(add_connected("Betina la corbina"))
        printf("Agrego a Betina\n");
    if(add_connected("CREO EN LA REENCARNACIÓN...(LA UÑA)"))
        printf("Agrego a la uña\n");
    if(add_connected("La solteria rige el corazon..."))
        printf("Agrego a la solteria\n");
    printf("ZISE --> %d \n",size());
    if(check_connected("Le solteria rige el corason.."))
        printf("Cualquiera se mando\n");
    if(check_connected("La solteria rige el corazon..."))
        printf("verifico correctamente solteria\n");
    if(disconnect("La solteria rige el corazon..."))
        printf("verifico correctamente solteria\n");
    printf("ZISE --> %d \n",size());    
    if(add_connected("Todos los perros van al cielo..."))
        printf("Agrego a perros\n");
    printf("ZISE --> %d \n",size());    
}
void main(){
    tester_list();
}

Solution

  • add_connected sets the global variable headlist to point to the local, automatic variable nuevoNodo. This goes out of scope when the function returns, meaning that behaviour in check_connected and all other functions which access headlist is undefined.

    I'm not sure I understand your question but would guess that you're creating a list whose elements all point to the same stack location (used for nuevoNodo in add_connected). If this is happening, note that this behaviour isn't guaranteed.

    You want nodes created inside add_connected to remain valid after the function returns so need to allocate memory dynamically:

    int add_connected(char *id_usuario){
        nodo* nuevoNodo = malloc(sizeof(*nuevoNodo));
        if (nuevoNodo == NULL) {
            printf("Error - out of memory\n");
            return FALSE;
        }
        strcpy(nuevoNodo->id_usuario, id_usuario);
        nuevoNodo->siguiente = headlist;
        headlist = nuevoNodo;
        size_var++;
        return TRUE;
    }
    

    At the end of your program, you'll now need to call a new function which calls free for each node in your list.