2012-04-16 87 views
1

我正在使用Visual Studio 2010,我知道它有一些特质。我希望不是这样。为链表节点中的字符串动态分配内存

这显然是一个更大的程序的一部分,但我试图简化它,所以我可以弄清楚我在做什么。

每次运行它时,calloc赋值都会解析为NULL,并退出程序。我在没有关于calloc的if语句的情况下尝试了它,并且得到了一个调试错误,所以我非常确定它是calloc是这个问题。

任何帮助,将不胜感激。

#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; 
} 

回答

2

我使用Visual Studio 2010中,我知道有一些特质。我希望不是这样。

这是一个分号:

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

无论什么calloc回报,以下块将被输入,你会打电话给exit


侧面说明,你可以写这样的:

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

尼斯赶上与代码关闭屏幕... – Attila 2012-04-16 00:35:38

+0

嗯...固定的,但现在它抛出一个调试错误。运行时检查失败#2 - 变量'str'周围的堆栈已损坏。 – lsiebert 2012-04-16 03:27:45