【问题标题】:sysmalloc: Assertion ....... failed. Aborted (core dumped)sysmalloc:断言.......失败。中止(核心转储)
【发布时间】:2021-08-14 10:04:34
【问题描述】:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>



typedef struct a{ 
    char * word ;
    int occurs;
    struct a * left;
    struct a * same;
    struct a * right; } Node; 
    
typedef Node * Node_ptr ;
typedef Node * TriTree ;

void inorder(TriTree x) {
    if(x==NULL) return;
    inorder(x->left);
    printf("%s(%d)--" , x->word, x->occurs);
    inorder(x->same);
    inorder(x->right);
    return;}

void strlower(char * lower){
    for (char *p = lower; *p; ++p) *p = tolower(*p);
    printf("%s\n",lower);
};
// 1
Node_ptr create(char * word){
    Node_ptr tmp_ptr;
    tmp_ptr = (Node_ptr)malloc(sizeof(Node_ptr));
    tmp_ptr-> word = word;
    tmp_ptr-> occurs = 1;
    tmp_ptr-> left = NULL;
    tmp_ptr-> same = NULL;
    tmp_ptr-> right = NULL;
    return tmp_ptr;
}


int main()
{
    char a[]="Stelios";

    strlower(&a);

    Node_ptr tmp;
    
    tmp = create(&a);
    printf(tmp->word);
    return 0;
}

我想写一个关于三叉树的结构以及创建节点、插入节点等的方法。

当我运行这段代码时,它很好!当我在 main() 中注释 // strlower(&a) 行时,我收到有关内存分配的错误,但我无法识别它。使用 Valgrind 的结果对我来说是模棱两可的。你能帮我处理这段特定的代码吗?

【问题讨论】:

  • tmp_ptr = (Node_ptr)malloc(sizeof(Node_ptr)); 显然是错误的。
  • 您在typedef 后面隐藏了一个指针类型。当您使用该类型分配内存时,这会反击您:malloc(sizeof(Node_ptr)); 不要在 typedefs 中隐藏指针。
  • 至少 gcc 11.1.1 明确 警告此代码中的 几个 错误。在提出关于 SO 的问题之前,请尝试做一些调查。
  • 我是 C 编程新手,我通常对指针感到困惑!很抱歉浪费您的时间,我应该搜索更多!但是感谢您的指导和友好的回答!

标签: arrays c tree malloc implicit-conversion


【解决方案1】:

这个内存分配

tmp_ptr = (Node_ptr)malloc(sizeof(Node_ptr));

错了。您正在尝试分配大小不正确的内存范围。

试试

tmp_ptr = (Node_ptr)malloc(sizeof(Node));

tmp_ptr = (Node_ptr)malloc(sizeof( *tmp_ptr ));

还有这些调用中的参数表达式

strlower(&a);
tmp = create(&a);

不正确。表达式的类型不是char *,而是char ( * )[sizeof( a )]

你需要写

strlower( a );
tmp = create( a );

【讨论】:

    猜你喜欢
    • 2020-12-08
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多