Search code examples
cstringstructstrcpy

copying a string in an array element of a struct


I have the following problem: I made this node structure

typedef struct NODE{
    struct NODE *sons[1024];             //this array will be used to store  children pointers
    char name[255];
    int leaf;                   

}NODE;

and this function to create a new node with a given name. The problem is that the first printf shows the right name, the second one doesn't. It seems like the for loop erases the name and I can't explain myself why...

NODE *AllocateNewNode( char *inputname) {
    NODE *newnode;
    newnode = (NODE *)malloc(sizeof(NODE));



    memset(newnode->name, '\0', sizeof(newnode->name));


    strcpy(newnode->name, inputname);    

    printf("node %s created\n", newnode->name);   //right name in the output


    int i = 0;
    for (i = 0; i <= 1024; i++) {

        newnode->sons[i] = NULL;
    }

    newnode->leaf = 1;


    printf("node %s created\n", newnode->name);        //no name in the output

    return newnode;
}

Solution

  • You're writing past the end of your sons array;

    Should be for (i = 0; i < 1024; i++) { since there are only 1024 elements in the array 0...1023.