Ben
Ben

Reputation: 31

Malloc memory for C string inside a structure

I currently have the following code.

    struct qnode
    {
        char *path;
        struct qnode *next;
    }

    typedef struct qnode Node;

My code fails at this point however when I try to malloc space for for within the struct qnode.

void add(Node *front, Node *back,char **path)
{
    /* Create the new node */
    Node *cur = (Node *)malloc(sizeof(Node));

    /* Verify node successfully created */
    if(cur)
    {
            /* Populate Members of Node */
            cur->path = malloc(strlen(*path)); /* fails here */
            printf("Malloc path success");
            cur->path = *path;

I have verified that strlen is indeed operating on the correct pointer and it is indeed returning the length of size. For some reason though I get a segmentation fault at this point and I don't understand why.

F.y.i This is part of an assignment HOWEVER this simple line of malloc is not something that was specifically assigned neither was using the C language. I am allowed to do c++ on the assignment but i've chosen C to get some more knowledge about the language.

Thanks for the Help!

Upvotes: 0

Views: 11118

Answers (1)

David Heffernan
David Heffernan

Reputation: 612854

You are not allocating enough memory. You need to leave room for the zero-terminator. You also must copy the contents of the string, not assign the pointer to the string. Both of these errors will lead to heap corruption and would explain your error. The code should be like this:

cur->path = malloc(strlen(*path)+1);
printf("Malloc path success");
strcpy(cur->path, *path);

You could of course use strdup if your system has it available, but note that it is not part of standard C.

Upvotes: 6

Related Questions