Home > Enterprise >  malloc size modified after changing stored value?
malloc size modified after changing stored value?

Time:04-16

I have a program that uses malloc to allocate a void-typed space for my program the value I pass to malloc is 1 so it should allocate 1 byte.

Now I cast the pointer to int and modify it's value to int (eg, 280). I am pretty sure that an int needs 4 bytes of memory to be stored, and I know for a fact that 280 is represented by at least 2 bytes

My expectations are that since I only have a pointer of 1 byte size, the whole integer wouldn't fit in that space, I thought that there would be an error or something (there were none) Then I thought that the integer was stored to RAM starting from the pointer start and exceeding the allocated memory, and since I would print the pointer of the allocated memory

I should get a value that represents the whole 1st byte of the number (in this case: 24)

BUT:

When I try to print the value of the pointer the value is still 280

Now what I am thinking is that somehow the program auto-allocates more size for that pointer

But I also think that's weird, could anyone explain what is happening here?

I would also like to know how to store ONLY the 1st byte of 280.

#include <iostream>

int main() {
  void* p = malloc(1); // This should allocate 1 byte
  *(int*)p = 280; // This should cast p to an integer, dereference it and set value to 280
  std::cout << *(int*)p << std::endl; // This prints 280 but I think it should print 24
  free(p);
}

The above is a pseudo-code that should do what a class I made does, instead of sending the whole class I just replaced the constructor, operator=, destructor to their actual code

EDIT:

I am using mingw32-g to compile the application

gcc version 6.3.0 (MinGW.org GCC-6.3.0-1)

CodePudding user response:

Malloc only allocates one byte but has no mechanism to avoid that you write on other memory addresses, by writing 4 bytes in the address of p you write the allocalted byte 3 other consecutive bytes. After that when you deference the pointer you read 4 bytes that are the same ones you just wrote. What you are doing is writing and reading on memory that the program probably isn't using, but this is undefined behaviour and you shouldn't ever do it as it can lead to segmentation faults.

  • Related