void pointers into a string not outputting properly in C

125 views Asked by At

Consider this code:

void foo(void* obj) {
    NodePtr node = malloc(sizeof(Node));
    char* word = (char*)obj;

    node->data= malloc(sizeof(char) * (strlen(word)+1));
    *((char*)(node->data)) = *(word); //assumed to be the problem

    printf(": %s\n", (node->data));
    printf(": %s\n", word);
}

What I basically want to do is set a void pointer attribute (data) of a node struct to a string value.

For some reason, the first print comes out as garbage, while the second print works out fine. I assume something is wrong with attempting to set the value of my node's data attribute to the value of word, the line indicated by the comment. I tried to typecast word into a char pointer, but that did not help. I tried to replace (word) with a char* typecast of obj as well.

One thing that should be noted is that the "gibberish" is actually the first letter of what it's supposed to be (ex: if printing out word prints out apples, then the other print statement gives a the first time, then in later function calls, it would be something like a^q.

I printed strlen(word) to make sure I was allocating the right amount of space, and that seems to check out.

1

There are 1 answers

0
Vlad from Moscow On BEST ANSWER

Write

node->data= malloc( strlen( word ) + 1 );
strcpy( (char*)node->data, word );

instead of

node->data= malloc(sizeof(char) * (strlen(word)+1));
*((char*)(node->data)) = *(word);