I have the following assignment:
Write a function in C that allocates block of memory and returns a pointer to the start of the memory under these conditions:
- All addresses in the block are divisible by 32
- Allocated at least the number of the bytes required
- Every cell in the block is initialized to zero
- No global variants, minimum complexity
Write another function that also releases the memory that you allocated. (You know that the aforesaid memory was allocated by the first function that you just wrote ).
Here is a debugging temporary solution:
"aligned_malloc.h":
#ifndef __ALIGNED_MALLOC_H__
#define __ALIGNED_MALLOC_H__
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define ALIGNMENT 16
#if ALIGNMENT > 255
#error "This 'void *aligned_malloc(size_t size)' function can only handle alignment < 256"
#endif
#if ALIGNMENT < 0
#error "This 'void *aligned_malloc(size_t size)' function can only handle a non negative alignment"
#endif
void* aligned_malloc(size_t size);
void aligned_free(void *aligned_p);
#endif /* __ALIGNED_MALLOC_H__ */
"alligned_malloc.c":
#include "aligned_malloc.h"
#undef DEBUG
#define DEBUG 1
int main()
{
size_t size = 0;
void *memblk = NULL;
do while (size > 0 )
{
printf("\nPlease enter in bytes the memory block size you want to allocate (0 to exit): ");
scanf("%d", &size);
memblk = aligned_malloc(size);
#ifdef DEBUG
printf("%s[%d]: memblk = 0x%x\n", __FUNCTION__, __LINE__, memblk);
#endif /* DEBUG */
}
if (memblk != NULL)
aligned_free(memblk);
return 0;
}
void *aligned_malloc(size_t size)
{
int i = 0;
void* memblk = malloc(size + ALIGNMENT);
printf ("\n%ld",(long)memblk);
//offset is the start address of memblk (long=8digit) modulo the ALIGNMENT
unsigned char offset = ALIGNMENT - ((long)memblk % ALIGNMENT);
printf ("\n%d",offset);
if (memblk == NULL)
return NULL;
/* O/W: */
#ifdef DEBUG
printf("%s[%d]: memblk = 0x%x\n", __FUNCTION__, __LINE__, memblk);
#endif /* DEBUG */
for (i = offset; i < size + ALIGNMENT; i++)
{
printf("%02d: %08d\n", i, memblk+i);
memblk[i] = 0;
}
*(memblk + offset - 1) = offset;
return (void*)(memblk + offset);
}
void aligned_free(void *aligned_p)
{
unsigned char offset = (unsigned char)(*((unsigned char *)aligned_p-1));
#ifdef DEBUG
printf("%s[%d]: offset = %d\n", __FUNCTION__, __LINE__, offset);
printf("%s[%d]: aligned_p-1 = 0x%x\n", __FUNCTION__, __LINE__, (unsigned char *)aligned_p-1);
printf("%s[%d]: aligned_p-offset = 0x%x\n", __FUNCTION__, __LINE__, aligned_p-offset);
#endif /* DEBUG */
free(aligned_p-offset);
}
Now I have several problems here:
- There is a compilation error in
main()
- I cannot catch how to use
calloc
instead ofmalloc
- If I use the
void*
is there an option to cast it to 32 bytes chunks?