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; 
}
nobody
  • 19,814
  • 17
  • 56
  • 77

1 Answers1

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);
}
0___________
  • 60,014
  • 4
  • 34
  • 74
  • WOW. That's crazy! Thx! Btw, what would be a better type to use in RAM instead of int 32 bit? –  Jun 20 '21 at 15:41
  • 1
    @pheianox RAM is usually addressed in **bytes** - thus `unsigned char` – 0___________ Jun 20 '21 at 15:44
  • 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? –  Jun 20 '21 at 15:54