Y
Yevgen Muntyan
Hey,
Consider the following code:
#include <stdlib.h>
#define MAGIC_NUMBER 64
void *my_malloc (size_t n)
{
char *result = malloc (n + MAGIC_NUMBER);
return result ? result + MAGIC_NUMBER : NULL;
}
void my_free (void *ptr)
{
if (ptr)
free ((char*) ptr - MAGIC_NUMBER);
}
It substitutes library malloc() and free() so that
calling free() on pointer returned by my_malloc()
is invalid (and results in nice abort here so I can detect
certain bugs, but that's not important).
Question is: does standard say that there is a value for MAGIC_NUMBER
such that the code above is valid? E.g. 64 works fine for me here,
17 doesn't.
Standard says that "The pointer returned if the allocation succeeds is
suitably aligned so that it may be assigned to a pointer to any type of
object and then used to access such an object or an array of such
objects in the space allocated", but it doesn't say if it's possible to
get another such a pointer from the malloc() result.
Best regards,
Yevgen
Consider the following code:
#include <stdlib.h>
#define MAGIC_NUMBER 64
void *my_malloc (size_t n)
{
char *result = malloc (n + MAGIC_NUMBER);
return result ? result + MAGIC_NUMBER : NULL;
}
void my_free (void *ptr)
{
if (ptr)
free ((char*) ptr - MAGIC_NUMBER);
}
It substitutes library malloc() and free() so that
calling free() on pointer returned by my_malloc()
is invalid (and results in nice abort here so I can detect
certain bugs, but that's not important).
Question is: does standard say that there is a value for MAGIC_NUMBER
such that the code above is valid? E.g. 64 works fine for me here,
17 doesn't.
Standard says that "The pointer returned if the allocation succeeds is
suitably aligned so that it may be assigned to a pointer to any type of
object and then used to access such an object or an array of such
objects in the space allocated", but it doesn't say if it's possible to
get another such a pointer from the malloc() result.
Best regards,
Yevgen