【问题标题】:Regarding pointers and malloc errors关于指针和 malloc 错误
【发布时间】:2015-03-18 01:23:37
【问题描述】:

我正在为玩具语言的编译器编写代码。这是代码的sn-p。在main 中有两个函数:createlistnode。当一个被注释掉时,另一个工作正常,但一起显示一个我不明白的错误。任何帮助表示赞赏。

#include <stdio.h>
#include <stdlib.h>

struct node {          //declaration for node
    int tokenno;
    struct node * next ;
};

struct node * newnode(int a)          // to create a new node
{
    struct node * new1  = (struct node *)malloc(sizeof(struct node));
    printf("\n malloc sucees");

    (*new1).tokenno = a ;
    (*new1).next = NULL ;
    printf("\new node sucess\n");
    return (new1);
};

struct firstlist{
    int size ;
    struct node * list[10];
};

typedef struct firstlist * plist; 

plist createlist(){                 //fun to create a first list
    int i ;                              

    plist p  = (plist) malloc(sizeof(struct firstlist));
    (*p).size = 10 ;
    for(i = 0 ; i <=10;i++){           //initializing list[i] to NULL
        (*p).list[i] = NULL ;
    }
    printf("\n created sucessfully");
    return p;
}

int main(){                         
    plist p ;
    //p = createlist(); // If you comment createlist the new node works fine
    //getfirstset(p);
    //insert(1,5,p);          
    newnode(2);
}

如果您注释掉newnode,那么createlist 可以正常工作,但一起显示以下错误:

a.out: malloc.c:2372: sysmalloc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) 
&& old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 *(sizeof(size_t))) - 1))
& ~((2 *(sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long) old_end & pagemask) == 0)' failed.
created sucessfullyAborted

【问题讨论】:

  • 显示什么错误?
  • 未定义行为:for(i = 0 ; i &lt;=10;i++) 超出了list 数组的范围。

标签: c


【解决方案1】:

它崩溃的原因是你在createlist函数中写入了数组的边界之外:

for(i = 0 ; i <= 10; i++)

应该是:

for(i = 0 ; i < 10; i++)

当你注释掉newnode函数时,它仍然不能正常工作,但它不会崩溃的原因是没有更多的内存访问会触发内存错误。

可能还有其他问题,但是改变这个,程序就会运行。

顺便说一句,您创建的节点永远不会放入列表中,但也许您还没有编写那部分代码(我猜它是插入函数)。

另外,你可以写p-&gt;size,而不是(*p).size,这对很多人来说更易读。

最后:当您声明 main 以返回 int 时,您应该以 return 0; 语句结束程序。

【讨论】:

    猜你喜欢
    • 2011-12-03
    • 2017-05-13
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多