Beau Horenberger
Beau Horenberger

Reputation: 41

Intentionally hiding memory via malloc

So I'm working on a small memory allocation package, and I've wanted the initialization of pointers to save the size of the space allocated as well as an indicator that it was allocated via one of my functions (which is the character 'q' before the size in memory). So, I've tried to do the following:

int qmem_alloc(unsigned num_bytes, void ** rslt){
  *rslt = malloc(num_bytes+sizeof(int)+sizeof(char));
  *((int*)rslt) = num_bytes;
  *(char*)(rslt+sizeof(int)) = 'q';
  rslt = rslt+sizeof(int) + sizeof(char);
  if(*rslt == NULL)
    return -1;
  else if(errno != 0){
    //Catch the rest of the errors
    return -2;
  }
  return 0;
}

However, it seems in my main function that the memory directly before the address of rslt does not contain what it should after being passed back. Am I doing something bad here by changing the pointer address?

Upvotes: 2

Views: 69

Answers (2)

dbush
dbush

Reputation: 223972

You're missing a level of indirection in a few places. Anyplace you use rslt before dereferencing you should be using *rslt:

int qmem_alloc(unsigned num_bytes, void ** rslt){
  *rslt = malloc(num_bytes+sizeof(int)+sizeof(char));
  if(*rslt == NULL)
    return -1;

  *((int*)*rslt) = num_bytes;
  *(char*)(*rslt+sizeof(int)) = 'q';
  *rslt = *rslt+sizeof(int) + sizeof(char);
  if(errno != 0){
    //Catch the rest of the errors
    return -2;
  }
  return 0;
}

Also, the memory returned by malloc is properly aligned for any use. Because you return sizeof(int)+sizeof(char) == 5 bytes past that (assuming a 4 byte int) which means the pointer you return is probably not. You'll want to add at least 3 more bytes to put the returned buffer on an 8 byte boundary.

Upvotes: 1

Kon
Kon

Reputation: 4099

Within your function rslt is the address of the pointer. You should not be modifying or even accessing that. If you're trying to change/read the address where the pointer is pointing to, than you need to use *rslt. If you're trying the modify/read the value of what the pointer is pointing to, you need to use **rslt.

@dbush describes the result of the above in code.

Upvotes: 0

Related Questions