A program was written by my friend and fellow software engineer Thomas to demonstrate how to use memory allocation using C programming language. Thank you Tom for sharing your code to us.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
void* alloc_mem(size_t size, const char *file, unsigned line)
{
assert(size > 0);
assert(file != NULL);
void* res = malloc(size);
if (res == NULL)
fprintf(stderr, "malloc failed at %s(%u)\n",file, line);
else {
fprintf(stderr, "alloc\t%u\t%u\t%s\t%u\n", (unsigned int)res,
size,file, line);
memset(res, 0xCC, size);
}
return res;
}
void free_mem(void *p, const char *file, unsigned line)
{
assert(p != NULL);
fprintf(stderr, "free\t%u\t?\t%s\t%u\n", (unsigned int)p, file, line);
}
#ifdef DEBUG
#define malloc(size) alloc_mem(size, __FILE__, __LINE__)
#define free(p) free_mem(p, __FILE__, __LINE__);
#endif
int f()
{
int *num = malloc(sizeof(int *));
return *num;
}
int main()
{
int *ip = malloc(sizeof(int *));
if (ip != NULL)
{
*ip = 11;
printf("*ip = %d\n", *ip);
}
printf("Num = %d\n", f());
free(ip);
//system("pause");
return EXIT_SUCCESS;