Search code examples
cstringvisual-studio-2010linked-listcalloc

dynamically allocate memory for a string in a linked list node


I'm using Visual Studio 2010, which I know has some idiosyncrasies. I'm hoping it's not that.

This is obviously part of a bigger program, but I've tried to simplify it so I could figure out what I'm doing.

Every time I run it, the calloc assignment resolves as NULL and I exit out of the program. I tried it without the if statement around calloc, and got a debug error, so I'm pretty sure it's calloc that is the issue.

Any help would be appreciated.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct NODE {
    char * x;
    struct NODE * link;
} NODE;

typedef struct {
    NODE * first;
} STRUCTURE;

NODE * insertNode (NODE * pList, NODE * pPre, char * string);

int main (void) {
   STRUCTURE  str[2];
   char * string = "blah";
    str[2].first = NULL;
    str[2].first = insertNode (str[2].first, str[2].first, string); 
    printf ("\n%s\n", str[2].first->x);
return 0;
}

NODE * insertNode (NODE * pList, NODE * pPre, char * string)
{
    //Local Declarations
    NODE * pNew;

    //Statements
    if ( !(pNew = (NODE*)malloc(sizeof(NODE)))) 
            printf ("\nMemory overflow in insert\n"),
                exit (100);
        if ( ( pNew->x = (char*)calloc((strlen(string) + 1), sizeof(char))) ==     NULL);
        {
            printf ("\nMemory overflow in string creation\n");
            exit (100);
        }
        strncpy(pNew->x, string, strlen(pNew->x)); 
    if (pPre == NULL) //first node in list
    {
        pNew->link = pList;
        pList = pNew;
    }
    else 
    {
        pNew->link = pPre->link;
        pPre->link = pNew;
    }

    return pList;
}

Solution

  • I'm using Visual Studio 2010, which I know has some idiosyncrasies. I'm hoping it's not that.

    It's a semicolon:

    if ( ( pNew->x = (char*)calloc((strlen(string) + 1), sizeof(char))) ==     NULL);
                                                                                    ^
    

    No matter what calloc returns, the following block will be entered and you'll call exit.


    Side note, you could write it like this:

    if (!(pNew->x = calloc(strlen(string) + 1, 1)))
        /* ... */