0

I'm creating a very simple dictionary structure in C and I'm not able to properly pass it to dictAdd function by reference. Something goes wrong inside the function and structure values get corrupted. See screenshots below. Everything is fine when I step into line 18, but when I get inside the function to line 19 the structure fields being to show inappropriate values.

Line 18

Line 18

Line 19

Line 19

Dictionary.h

typedef struct DictionaryStruct
{
    int *arr;
    int arrLen;
} Dictionary;

Dictionary *dictCreate(int arrLen);
int dictAdd(Dictionary *dict, char *key, char *val);

Dictionary.c

#include "Utils.h"
#include "Dictionary.h"

Dictionary *dictCreate(int arrLen)
{
    int *arr = createIntArray(arrLen);
    for (int i = 0; i < arrLen; ++i)
    {
        arr[i] = '\0';
    }

    Dictionary dict;
    dict.arr = arr;
    dict.arrLen = arrLen;
    return &dict;
}

int dictAdd(Dictionary *dict, char *key, char *val) {
    int hash = getHash(key, dict->arrLen);
    dict->arr[hash] = val;
}

Main.c

#include <stdio.h>
#include <stdlib.h>
#include "Utils.h"
#include "Dictionary.h"

int main() {
    Dictionary *dictPtr = dictCreate(5);
    dictAdd(dictPtr, "key1", "Hello");
    char *value1 = dictGet(dictPtr, "key1");
    printf("%s", value1);

    printf("Press any key to exit\n");
    getchar();
}
opewix
  • 4,993
  • 1
  • 20
  • 42

1 Answers1

3

You're returning a pointer to a local. Dereferencing a pointer after the end of its target's lifetime is undefined behavior.

Your dictCreate should heap-allocate the Dictionary structure as well (in addition to heap-allocating the int array).

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142