京东的售后电话时间:最近的作业题不会做啊~~~请高手帮忙orz

来源:百度文库 编辑:查人人中国名人网 时间:2024/04/29 06:52:57
是叫实现一个DebugMalloc的程序
下面是几个我觉得可能会用到的原代码,要求只改动debugmalloc.c来实现
使用这段代码:
char *str = (char *) MALLOC(8);
strcpy(str, "12345678");
FREE(str);

会返回一个信息
Error: Ending edge of the payload has been overwritten.
in block allocated at driver.c, line 21
and freed at driver.c, line 23

具体是哪个Error信息是有专门的两个函数根据错误号处理的
Error #1: Writing past the beginning of the user's block (through the fence)
Error #2: Writing past the end of the user's block (through the fence)
Error #3: Corrupting the header information
Error #4: Attempting to free an unallocated or already-freed block
Error #5: Memory leak detection (user can use ALLOCATEDSIZE to check for leaks at the end of the program)

----------------------------------------------------
//debugmalloc.h
#ifndef DEBUGMALLOC_H
#define DEBUGMALLOC_H

#include <stdlib.h>

/* Macros that will call the wrapper functions with
the current filename and line number */

#define MALLOC(s) MyMalloc(s, __FILE__, __LINE__)
#define FREE(p) MyFree(p, __FILE__, __LINE__)

/* Wrappers for malloc and free. You will implement
these functions. */

void *MyMalloc(size_t size, char *filename, int linenumber);
void MyFree(void *ptr, char *filename, int linenumber);

/* Required function for detecting memory leaks */

int AllocatedSize(); /* returns number of bytes allocated */

/* Optional functions if you wish to implement the global list */

void PrintAllocatedBlocks();
int HeapCheck(); /* returns 0 if all blocks have not been corrupted,
-1 if an error is detected */

#endif

//debugmalloc.c
#include <stdlib.h>
#include <string.h>
#include "debugmalloc.h"
#include "dmhelper.h"
#include <stdio.h>

/* Wrappers for malloc and free */
void *MyMalloc(size_t size, char *filename, int linenumber) {
return size;
}

void MyFree(void *ptr, char *filename, int linenumber) {
free(ptr);
}

/* returns number of bytes allocated using MyMalloc/MyFree:
used as a debugging tool to test for memory leaks */
int AllocatedSize() {
return 0;
}

/* Optional functions */

/* Prints a list of all allocated blocks with the
filename/line number when they were MALLOC'd */
void PrintAllocatedBlocks() {
return;
}

/* Goes through the currently allocated blocks and checks
to see if they are all valid.
Returns -1 if it receives an error, 0 if all blocks are
okay.
*/
int HeapCheck() {
return 0;
}