Basically I am trying to build a hash structure of cstrings that I can re-assign the member stringnode_ref *nodes to a larger dimension array (malloc a new one, re-hash the existing values, and delete the old one) when the hash begins to fill up.
stringtable.c:
#include <stdio.h>
#include "stringtable.h"
struct stringnode{
hashcode_t key;
cstring value;
};
struct stringtable{
size_t dim;
size_t numEntries;
stringnode_ref *nodes;
};
stringtable_ref new_stringtable(){
size_t index = 0;
stringtable_ref sTable = malloc(sizeof(struct stringtable));
sTable->dim = 31;
sTable->numEntries;
sTable->nodes = malloc(31 * sizeof(struct stringnode));
for( index = 0; index < 31; index++ ){
sTable->nodes[index]->key = 0;
sTable->nodes[index]->value = NULL;
}
return sTable;
}
stringtable.h:
#ifndef __STRINGTABLE_H__
#define __STRINGTABLE_H__
#include <stdlib.h>
#include <inttypes.h>
typedef char *cstring;
typedef uint32_t hashcode_t;
typedef stringtable *stringtable_ref;
typedef stringnode *stringnode_ref;
stringtable_ref new_stringtable();
#endif // __STRINGTABLE_H__
oc.c:
#include <stdlib.h>
#include <stdio.h>
#include "stringtable.h"
int main( int argc, char **argv ){
stringtable_ref table = new_stringtable();
return EXIT_SUCCESS;
}
compiling with:
gcc -g -O0 -Wall -Wextra -std=gnu99 -c stringtable.c
gcc -g -O0 -Wall -Wextra -std=gnu99 -c oc.c
gcc -g -O0 -Wall -Wextra -std=gnu99 -o oc stringtable.o oc.o
this all compiles fine with no errors but upon declaring stringtable_ref table = new_stringtable(); in the main(), the program segfaults at sTable->nodes[index]->key = 0;. Any thoughts?
here’s the problem: the segfault occurs because you don’t allocate memory for
sTable-nodes[index], so it may be garbage (when I examined your code on GDB under OS X, it was actuallyNULL).Solution: add the following line as the first line of the body of the
forloop: