结构体内部 C 字符串的 Malloc 内存

发布于 2024-12-09 08:40:27 字数 802 浏览 1 评论 0原文

我目前有以下代码。

    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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

折戟 2024-12-16 08:40:27

您没有分配足够的内存。您需要为零终止符留出空间。您还必须复制字符串的内容,而不是将指针分配给字符串。这两个错误都会导致堆损坏并解释您的错误。代码应如下所示:

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

如果您的系统可用,您当然可以使用 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:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文