I am developing C89 on Visual Studio 2010 Ultimate Beta (Win 7). I don't think I'm using malloc()
correctly. I am new to C, so please excuse the beginner question.
The goal of my program is to count the occurrence of words in **argv
using a tree.
hist.c
#include "tree.h"
#include <stdlib.h>
int main(int argc, char *argv[]) {
unsigned int i;
struct tree *tree;
tree = new_tree();
for (i = 1; i < argc; i++) {
tree_add(tree, argv[i]);
}
tree_dump(tree);
tree_free(tree);
return 0;
}
tree_add.c:
#include "tree.h"
#include <stdlib.h>
#include <string.h>
struct tree *tree_add(struct tree *tree, char *value) {
if (tree == NULL) {
tree = new_tree();
tree->value = value;
tree->count = 0;
}
else if (tree->value == NULL) {
tree->value = value;
}
else if (tree->value == value) {
tree->count++;
}
else if (strcmp(value, tree->value) < 0) {
tree_add(tree->left, value);
}
else if (strcmp(value, tree->value) > 0) {
tree_add(tree->right, value);
}
}
struct tree *new_tree() {
struct tree * tree;
tree = malloc(sizeof *tree);
tree->left = NULL;
tree->right = NULL;
tree->value = NULL;
tree->count = 0;
return tree;
}
The error I get is:
0xC0000005: Access violation reading location 0x00000000.
I looked online, and it appears that this error is caused by trying to access improperly allocated memory. So what am I doing wrong?
UPDATED code to reflect comments. Now I have a new problem. This condition is not working properly when value == "x"
and tree->value == "x"
else if (tree->value == value) {
In the debugger, I see that tree->value
is 0x00553373 "x" char *
, whereas value
is 0x00553375 "x" char *
. The hex value is different in the last digit. What is wrong here? Am I checking for string equality incorrectly?