0

I want to build a general tree in C. The node of the tree has an array of strings and a list of children.

typedef struct treeNode {
    int numOfChildren;
    char** commands;
    struct treeNode** children;
} tNode;

tNode* head = (tNode*) malloc(sizeof(tNode));

tNode* node0 = (tNode*) malloc(sizeof(tNode));
tNode* node1 = (tNode*) malloc(sizeof(tNode));
node1->commands[0] = "hello";

When compile using gcc in Linux, it is giving me a segmentation error. Can somebody tell me what is wrong?

user2895478
  • 383
  • 4
  • 15
  • [Please don't cast the result of malloc in C](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). Also note that you didn't allocate any memory for `commands` or `children`. – Paul R Feb 07 '14 at 21:39

1 Answers1

1

I'm going with

char** commands;

Is the wrong type. This is a pointer to a pointer that holds a char. So that when you do

node1->commands[0] = "hello";

It gets the address of hello and then interprets the contents at that address as a pointer to the string you thought you wanted to assign, and assigns that value to commands[0], which is really just commands. Which if course is computer gibberish and ends in your segmentation fault.

Either you have to have declare and use

char* commands;
...
node1->commands = "hello";

Or you need to create some intermediate pointer to assign to commands, such as mallocing an additional block of memory somewhere, and filling that pointer with the address that points to hello.

For example

#define MAXNUMCMDS 10
...
char** commands;
…
tNode* node1 = malloc(sizeof(tNode));   
node1->commands = malloc(MAXNUMCMDS * sizeof(char*));
node1->commands[0] = "Hello";
node1->commands[1] = "World";
node1->commands[2] = "here";
node1->commands[3] = "is";
node1->commands[4] = "an";
node1->commands[5] = "example";
node1->commands[6] = "of";
node1->commands[7] = "an";
node1->commands[8] = "array of";
node1->commands[9] = "char*";

Of course, assigning something to commands[10] would be a big big mistake, as you would be writing past the end of the assigned array.

Also now when you free node1, you will also have to free commands (and technically you need to free commands first)

Peter M
  • 7,309
  • 3
  • 50
  • 91