-1

I have this (strange) problem:

I'm implementing a sort of hash table and I have to insert some predefined elements into it and here is the problem:

if I push these new entries with a function defined in a source file, the find function doesn't work, but if I push them with the same function but defined in the main function file it all works.

Here is some code:

HEADER

//SymbolTable.h

typedef struct element
{
    const char* name;
    int address;
    struct element* prev;
} element_t;

typedef element_t* elemPoint;

//definition of functions

SOURCE

//SymbolTable.c

//include libraries and header file

static elemPoint last;

static elemPoint iterator;

void init()
{
    last = NULL;
    pushSymbol("SP",0);
    pushSymbol("LCL",1);
    pushSymbol("ARG",2);
    pushSymbol("THIS",3);
    pushSymbol("THAT",4);
}

void pushSymbol(const char* nameVar, int addressVar)
{
    elemPoint pushed = malloc(sizeof(element_t));
    pushed-> prev = last;
    pushed-> name = nameVar;
    pushed-> address = addressVar;

    last = pushed;
}

int findName(const char* nameVar)
{
    iterator = last;

    while(iterator!=NULL)
    {
        if(iterator->name == nameVar)
        {
            return 1;
        }
        else
        {
            iterator = iterator->prev;
        }
    }

    return 0;
}

MAIN

//main.c

//include libraries and header

int main()
{
    init();
    if(findName("LCL")) puts("true");
    else puts("false");
}

The output of this code is false, but if I put the entire init() function in the main module the output is true.

So I thought that maybe the problem was with the iterator variable.

And there's the strange thing, while debugging I put a printf of iterator->name right after the while in the findName function, and the output was correct (all the elements name were printed on the std output).

So now I'm assuming that the problem is in the comparison iterator->name == nameVar, but I can't understand why.

1 Answers1

2

You are comparing strings with ==. In C, since strings are nothing but char *, this doesn't mean equality as a sequences of characters but equality of pointers, that is storage places. It seems that your compiler decide that if the same string is used twice in the main function it can be reused but not if it is used in a different function. Note that this is just the compiler trying to save memory...

The solution is to use strcmp instead:

if (strcmp(iterator->name, nameVar) == 0)
hivert
  • 10,579
  • 3
  • 31
  • 56