0

Suppose I have this struct representing a virtual machine. Please, check out my init() method. In the init() method I am allocating some space in the heap for the state of my virtual machine. But, something doesn't seem right. I am allocating space first for my state (struct), then for the RAM (array of type int), which is already inside of my struct. Is it okay? or I'm doing something wrong?

My question is how do I property allocate memory for the array inside of struct in the heap.

typedef struct { int* ram; int pc; } vm_t; vm_t* init(int ram_size) { vm_t* vm = (vm_t*)malloc(sizeof(vm_t)); vm->ram = (int*)malloc(ram_size * sizeof(int)); vm->pc = 0; return vm; } 
4
  • 3
    your code is correct. The usual advice is to not cast the result of malloc, but it's not necessarily wrong to do so. Commented Jun 20, 2021 at 15:05
  • 3
    (also, you should check for NULL returns from malloc) Commented Jun 20, 2021 at 15:05
  • @PaulHankin Thx, sir. Why not to cast the result of malloc, btw? Is there any advantages or doing that? Commented Jun 20, 2021 at 15:07
  • 1
    There's a whole question on whether or not to cast malloc: see Do I cast the result of malloc? Commented Jun 20, 2021 at 15:08

1 Answer 1

1

I would do it a bit different way. Only one malloc and free needed.

typedef struct { size_t pc; int ram[]; } vm_t; vm_t* init(size_t ram_size) { vm_t *vm = malloc(sizeof(*vm) + ram_size * sizeof(vm -> ram[0])); if(vm) vm -> pc = 0; return vm; } 

Some remarks: use size_t for sizes, always checks the result of malloc. Use objects not types in the sizeof. When you change the type memory allocation will not have to be changed.

I do not know why RAM has int type but it does not matter in this question.

EDIT. How to access. Example how to read the ram

int read_RAM(vm_t *vm, size_t address) { return vm -> ram[address]; } int read_RAM1(vm_t *vm, size_t address) { return *(vm -> ram + address); } 
Sign up to request clarification or add additional context in comments.

3 Comments

WOW. That's crazy! Thx! Btw, what would be a better type to use in RAM instead of int 32 bit?
@pheianox RAM is usually addressed in bytes - thus unsigned char
On more question. In you example, how do I set the ram pointer? Like, you only allocated memory, and inited program counter, how do I init the ram so it points to its beggining?