I am trying to use the first few bytes of a section of memory on the heap to store meta-data about the section memory using C language (not C++).
The heap space is created using:
char* start_mem = (char*)malloc(10*sizeof(char)); //10 bytes of memory
Now, I'm trying to place a 'meta' struct in the first 4 bytes of allocated heap space.
typedef struct{
int test;
}meta_t;
This is a test code I'm using to just understand how to do it before I implement it in the larger code.
test #include <stdio.h>
typedef struct{
int test;
} meta_t;
int main(void) {
char* start_mem = (char*)malloc(10*sizeof(char));
meta_t meta;
meta.test = 123;
return 0;
}
Side note: Why does this type cast work:
int test = 123;
char c = (char) test;
but this type cast doesn't?:
meta_t meta;
meta.test = 123;
char c = (char) meta;
The main question is how can I fit the 'meta' data type (4 bytes) in to four char sized (1 byte) spaces at the start of the start_mem?
FYI - This is a small part of a larger project in a data structures class. Having said that there is no need to reply with "Why would you even bother to do this?" or "You could just use function_abc() and do the same thing." Restrictions have been set (i.e. a single use of malloc() ) and I would like to follow them.
You could use memcpy:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
int test;
} meta_t;
int main() {
char *start_mem = malloc(10);
meta_t meta;
meta.test = 123;
memcpy(start_mem, &meta, sizeof(meta));
printf("Saved: %d\n", ((meta_t *)(start_mem))->test);
return 0;
}