malloc.c:2394: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)’ failed.
这是由于越界访问了动态分配的内存。
Graph GraphInit(int v)
int i = 0;
Graph G = (Graph)malloc(sizeof(struct graph));
G->v = v;
G->E = 0;
G->adj = (Node *)malloc( v * sizeof(Node));
for(i = 0 ; i < v ; i++){
G->adj[v] = NULL;
return G;
将
G->adj[v] = NULL;
修改为G->adj[i] = NULL;即可。
这种内存分配错误越界访问错误一定得时刻注意着。
malloc.c:2394: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)
67. C/C++ 误区一:void main() 373
68. C/C++ 误区二:fflush(stdin) 376
69. C/C++ 误区三:强制转换 malloc() 的返回值 380
70. C/C++ 误区四:char c = getchar(); 381
71. C/C++ 误区五:检查 new 的返回值 383
72. C 是 C++ 的子集吗? 384
73. C和C++的区别是什么? 387
74. 无条件循环 388
75. 产生随机数的方法 389
76. 顺序表及其操作 390
77. 单链表的实现及其操作 391
78. 双向链表 395
79. 程序员数据结构笔记 399
80. Hashtable和HashMap的区别 408
81. hash 表学习笔记 410
82. C程序设计常用算法源代码 412
83. C语言有头结点链表的经典实现 419
84. C语言惠通面试题 428
85. C语言常用宏定义 450
sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size)
(strlen(layerName) + 1)为字符串申请内存的,用strlen时,需要+1
帮我用c语言写一段代码,要求如下:函数名为void * malloc_safe;形式参数为int size; Like malloc, allocate space of size bytes on the heap. The differences are that a. anything is wrong, quit the program; b. param is int, unlike the unsigned int parameter of malloc. It is a sensitive and alerting version of malloc. ;If size is 0 or negative, some error message is printed and exit the program. If anything wrong ( malloc returns NULL), print some error message and exit the whole program. When there is no problem, return the address of the first byte of the allocated space on the heap. ( It calls malloc() or calloc() for space allocation). ;if the function is defined as: void *malloc_safe(Uint size); then malloc_safe(-5) will not have error messages. instead, 4294967291 byes will be allocated, causing a lot of confusion.
该代码中,我们先检查输入的 size 是否为正数,如果不是,就输出错误信息并退出程序。然后使用 malloc 函数分配内存,如果返回 NULL,则输出错误信息并退出程序。如果一切正常,则返回分配内存的首地址。
请注意,在使用 malloc_safe 函数分配内存后,调用者需要负责在使用完毕后调用 free 函数释放内存。