结构体内部 C 字符串的 Malloc 内存
我目前有以下代码。
struct qnode
{
char *path;
struct qnode *next;
}
typedef struct qnode Node;
然而,当我尝试在 struct qnode 内为 for 分配空间时,我的代码此时失败了。
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;
我已经验证 strlen 确实在正确的指针上进行操作,并且它确实返回了 size 的长度。由于某种原因,虽然我此时遇到了分段错误,但我不明白为什么。
仅供参考,这是分配的一部分,但是这个简单的 malloc 行并不是专门分配的,也不是使用 C 语言的。我可以在作业中使用 C++,但我选择 C 是为了获得有关该语言的更多知识。
感谢您的帮助!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您没有分配足够的内存。您需要为零终止符留出空间。您还必须复制字符串的内容,而不是将指针分配给字符串。这两个错误都会导致堆损坏并解释您的错误。代码应如下所示:
如果您的系统可用,您当然可以使用
strdup
,但请注意,它不是标准 C 的一部分。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:
You could of course use
strdup
if your system has it available, but note that it is not part of standard C.