tests/malloc: cleanup

- make local functions / variables static
- adhere to the 80 column limit
- don't increment total if head could not be allocated
- allow to overwrite CHUNK_SIZE
This commit is contained in:
Benjamin Valentin 2019-09-13 00:35:47 +02:00
parent 66ce29d94c
commit 769fe44f6d

View File

@ -23,36 +23,40 @@
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#ifndef CHUNK_SIZE
#define CHUNK_SIZE 1024 #define CHUNK_SIZE 1024
#endif
struct node { struct node {
struct node *next; struct node *next;
void *ptr; void *ptr;
}; };
int total = 0; static int total = 0;
void fill_memory(struct node *head) static void fill_memory(struct node *head)
{ {
while (head && (head->ptr = malloc(CHUNK_SIZE))) { while (head && (head->ptr = malloc(CHUNK_SIZE))) {
printf("Allocated %d Bytes at 0x%p, total %d\n", CHUNK_SIZE, head->ptr, total += CHUNK_SIZE); printf("Allocated %d Bytes at 0x%p, total %d\n",
CHUNK_SIZE, head->ptr, total += CHUNK_SIZE);
memset(head->ptr, '@', CHUNK_SIZE); memset(head->ptr, '@', CHUNK_SIZE);
head = head->next = malloc(sizeof(struct node)); head = head->next = malloc(sizeof(struct node));
if (head) { if (head) {
head->ptr = 0; total += sizeof(struct node);
head->ptr = 0;
head->next = 0; head->next = 0;
} }
total += sizeof(struct node);
} }
} }
void free_memory(struct node *head) static void free_memory(struct node *head)
{ {
struct node *old_head; struct node *old_head;
while (head) { while (head) {
if (head->ptr) { if (head->ptr) {
printf("Free %d Bytes at 0x%p, total %d\n", CHUNK_SIZE, head->ptr, total -= CHUNK_SIZE); printf("Free %d Bytes at 0x%p, total %d\n",
CHUNK_SIZE, head->ptr, total -= CHUNK_SIZE);
free(head->ptr); free(head->ptr);
} }