Advertisement

Memory and Pointers

Started by December 04, 2000 10:03 PM
4 comments, last by vbisme 24 years, 1 month ago
Let''s say:
  
BYTE *pOne;
BYTE *pTwo;

pOne = (BYTE*)malloc(10);  //allocating 10 bytes

pTwo = (int*)(pOne);       //let pTwo points to the first 4 bytes

                           //(an int) of pOne

free(pOne);                //is pTwo freed too?

  
is data that the second pointer points to lost with the call to free() ?
In this case, the memory that pOne was pointing to would be freed, and since pTwo is pointing to that same memory spot, then yes, they would both be freed - but watch out - the pointers are not NULL at this point, so you would not get any errors while compiling, but boy at runtime, if you try to access pOne or pTwo after you have freed one of them, you''ll be accessing memory you shouldn''t be : )
Advertisement
malloc and free have an internal data structure that keeps track of the memory allocated and the address of that memory, so it doesn''t matter how that memory is represented, as an int pointer, char pointer, or whatever, free will know how much to free. And yes, since they''re both pointing to the same area of memory, the second pointer is pointing at freed memory.

(By the way, you should not cast malloc. It can hide errors, like forgetting to include stdlib.h)
Yes, and since you''re casting to an int, you surely meant

BYTE *pOne;
int *pTwo;

right ?

-Markus-
Professional C++ and .NET developer trying to break into indie game development.
Follow my progress: http://blog.nuclex-games.com/ or Twitter - Topics: Ogre3D, Blender, game architecture tips & code snippets.
How do you get the size(number of bytes) that is allocated by malloc() from a pointer? Like how much memory that pointer is pointing to?
The way malloc and free work is implementation-specific, so you can''t find out how much memory has been allocated automatically. The only way to find this out is allocated is to write your own wrappers for malloc and free, and store the size allocated. For example:

  void *my_malloc(int size){    int *data = (int *)malloc(sizeof(int)+size);    *data = size;  // store the size at start of buffer    return (void*)(data+1);}void my_free(void *ptr){    free((int*)ptr-1);}int size(void *ptr){    return *((int*)ptr-1);}  


Dave

This topic is closed to new replies.

Advertisement