0

I just have a quick question regarding how a char array works in regards to a memory pool and allocating pointers of other variable types to it. I am working on an assignment which uses a char array for a memory pool and I need to be able to allocate pointers to it, and I have read some info on the subject but am not quite understanding one part which is how the actual allocation works such as:

const int poolSize = 60000;
char pool[poolSize];

void* allocate(int aSize)
{

   //.....

 return ((void*) 0);
}

long* pointer;
pointer = (long *) allocate(sizeof(long));
*pointer = 0xDEEDEEEF;

I just don't quite get exactly how this works since a char is 1 byte while a long should be 4 and so how does something like this work when I need to allocate 4 spots in the array to the one long pointer variable? Also feel free to give examples and explanations but please don't give away how the entire program should work as I would like to figure it out myself once I understand exactly how this part works. Thanks

eddie
  • 1,252
  • 3
  • 15
  • 20
zfetters
  • 447
  • 2
  • 11
  • In addition to your `pool`, your going to need some way to track which bytes are used. `allocate` could then find `aSize` available contiguous bytes, return the pointer to the beginning of it, and mark those bytes as used. – Drew Dormann Feb 23 '13 at 07:40
  • so if i were to do something such as initialize all all spots in the pool to char 'F' for instance then i could check for a certain number of F's in a row to know they are emtpy and set them to 'T' or something else to mark them as filled then this would allow me to track this. Would it be better to initialize them like this or some other way? Then for deallocation would i just return a pointer to the first byte of the set and to the variable and then go back through and mark the byte used by it as free again? – zfetters Feb 23 '13 at 07:47
  • You should check out the C++ allocator concept. – Alex Chamberlain Feb 23 '13 at 08:53

1 Answers1

2

Memory allocation is independent of type i.e whether it is long/char.etc But thing is, it is quantified on "bytes". And char is the only data type which takes one byte memory.

Its on your program how you treat the allocated memory. For ex

char s[4]={0,0,0,'A'};
int *p = (int*)s; //treating those 4 bytes as int
printf("%d",*p); //will print 65  

I will suggest you to watch first 4-5 Stan-Ford Programming Paradigm lectures. Memory allocation is explained incredibly well in those lectures. You can also refer to Chapter 8 of The C programming language -by Denis Ritchie

Aditya Kumar
  • 297
  • 2
  • 3
  • 10