Created
April 1, 2013 14:51
-
-
Save reagent/5285365 to your computer and use it in GitHub Desktop.
Implementation of realloc / malloc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
realloc | |
*.o | |
*.dSYM |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CFLAGS=-g -Wall -Wextra | |
all: realloc | |
clean: | |
rm -rf *.o realloc *.dSYM |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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