Skip to content

Instantly share code, notes, and snippets.

@reagent
Created April 1, 2013 14:51
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reagent/5285365 to your computer and use it in GitHub Desktop.
Save reagent/5285365 to your computer and use it in GitHub Desktop.
Implementation of realloc / malloc
realloc
*.o
*.dSYM
CFLAGS=-g -Wall -Wextra
all: realloc
clean:
rm -rf *.o realloc *.dSYM
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <malloc/malloc.h>
void print_size(void *ptr);
void *
realloc(void * ptr, size_t size)
{
void *new;
if (!ptr) {
new = malloc(size);
if (!new) { goto error; }
} else {
if (malloc_size(ptr) < size) {
new = malloc(size);
if (!new) { goto error; }
memcpy(new, ptr, malloc_size(ptr));
free(ptr);
} else {
new = ptr;
}
}
return new;
error:
return NULL;
}
void *
calloc(size_t count, size_t size)
{
size_t alloc_size = count * size;
void *new = malloc(alloc_size);
if (new) {
memset(new, 0, alloc_size);
return new;
}
return NULL;
}
int
main()
{
char *tmp = calloc(2, sizeof(char *));
print_size(tmp);
tmp = realloc(tmp, 200 * sizeof(char *));
print_size(tmp);
tmp[0] = '.';
tmp[1] = '\0';
printf("Content: %s\n", tmp);
tmp = realloc(tmp, 1 * sizeof(char *));
print_size(tmp);
printf("Content: %s\n", tmp);
free(tmp);
return 0;
}
void
print_size(void *ptr)
{
if (ptr) {
printf("ptr segment size: %ld\n", malloc_size(ptr));
} else {
printf("ptr is NULL\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment