zoukankan      html  css  js  c++  java
  • free一个无效指针

    1. 错误描述:   刚才写了一个删除单链表的结点函数, 参数是 指向链表的指针和链表中指定删除的结点的指针。  当我free这个待删除的结点, 结果报错。  

    2. 为什么会报错?

        我查了查MSDN, 看到“Attepmting  to free an invalid pointer (a pointer to a memory block that was not allocated by calloc, malloc, or realloc) may affect subsequent allocation requests and cause errors”。 意思是  只能free掉由calloc,malloc, realloc申请的内存。 而我试图释放定义的结点所占内存。 

    3. 错误代码

    status
    Delete( struct NODE **rootp, struct NODE *node )
    {
        PNode p_node = NULL;
    
        if ( rootp == NULL ){
            printf( "没有可操作的链表
    " );
            return FALSE;
        }
    
        if ( node == NULL ){
            printf( "没有指定删除的结点
    " );
            return FALSE;
        }
    
        if ( node == *rootp ){        
            *rootp = node->next;    /* 删除第一个结点 */
    
        }else{
            for ( p_node = *rootp;
                    p_node != NULL  &&  p_node->next != node;
                        p_node = p_node->next );
    
                        if ( p_node == NULL ){
                            printf( "指定删除的结点不存在
    " );
                            return FALSE;
    
                        }else{
                            p_node->next = node->next;    /* 删除中间结点或尾结点 */
                        }
                        
        }
        
    /*  问题在这里      */
        free( node );
        node = NULL;
        return TRUE;
    }
    
    /* main函数 */
    void
    main ()
    {
        PNode list = (PNode) malloc ( sizeof( struct NODE ) );
        PNode p = NULL;
        Node one, two, three, four;
        
        one.data = 1;
        two.data = 2;
        three.data = 3;
        four.data = 4;
        one.next = &two;
        two.next = &three;
        three.next = &four;
        four.next = NULL;
    
    
        list->next = &one;
        p = &three;
    
        if ( Delete( &list, p ) == TRUE ){
            Put( list );
        }else{
            printf( "删除失败
    " );
        }
    }
  • 相关阅读:
    知识收集
    代码片_笔记
    北理工软件学院2016程序设计方法与实践
    内存的初始化与清零问题
    LeetCode第七题
    KMP算法C代码
    在64位Linux上安装32位gmp大数库
    ASN1编码中的OID
    迷宫问题
    64位linux编译32位程序
  • 原文地址:https://www.cnblogs.com/the-one/p/4654623.html
Copyright © 2011-2022 走看看