我不知道如何将字符串从inputString
复制到newNode->data
。
我的结构如下:
typedef struct node {
char *data;
struct node *left;
struct node *right;
} node;
问题函数如下:
node* addToTree(char inputString[]) {
node *newNode;
if ((newNode = malloc(sizeof(node*))) == NULL) {
printf("Error: could not allocate memory");
exit(-1);
}
if ((newNode->data = malloc(strlen(inputString) + 1)) == NULL) {
printf("Error: could not allocate memory");
exit(-1);
}
/* This line of code doesn't seem to copy anything to newNode->data.
This is the way I believe should work, however I don't understand what the
problem with it is. I have tried strlcpy and strncpy as well. */
strcpy(newNode->data, inputString);
/* The line below here seems to work when I print the value
within the function, but some of the values are garbage when
I try to use them later on in the program. */
newNode->data = inputString;
newNode->left = NULL;
newNode->right = NULL;
printf("Input string: %s\n", inputString);
printf("New node data: %s\n", newNode->data);
return newNode;
}
答案 0 :(得分:4)
您的sizeof(node*)
并不代表您需要的尺寸。
newnode = malloc(sizeof(node*)) // wrong
newnode = malloc(sizeof (node)) // correct
newnode = malloc(sizeof *newNode) // better
为什么sizeof *newNode
更好?
因为它防止了类型更改后在两个处意外忘记更新代码
struct node {
char *data;
struct node *next;
struct node *prev;
};
struct nodeEx {
char *data;
size_t len;
struct nodeEx *next;
struct nodeEx *prev;
};
struct nodeEx *newnode = malloc(sizeof (struct node)); // wrong
struct nodeEx *newnode = malloc(sizeof *newnode); // correct
答案 1 :(得分:1)
以下行未分配所需的内存量,而是分配了等于指向 node
的指针的大小的内存。
if ((newNode = malloc(sizeof(node*))) == NULL)
因此您的strcpy
失败,因为没有可复制的内存。
将以上内容更改为:
if ((newNode = malloc(sizeof(node))) == NULL)
执行以下操作后会发生未定义的行为,因为代表inputString
的内存可以被覆盖,这就是为什么以后会得到垃圾值的原因。
newNode->data = inputString;
您可以查看此question的最佳答案,以获取更多信息。
答案 2 :(得分:0)
newNode->data = inputString;
不正确,它会覆盖之前malloc
版的内存。
if ((newNode->data = malloc(strlen(inputString) + 1)) == NULL) {
printf("Error: could not allocate memory");
exit(-1);
}
strcpy(newNode->data, inputString);
足以分配内存并将字符串复制到其中。