A question about memory allocation
I've just got a quick question about how memory is stored on the computer..
Say you had 16bytes of memory, had 3 arrays of characters, one 4 bytes, one 2 bytes and one 6 bytes long:
cstr1 = (char*)malloc(sizeof(char)*4)
cstr2 = (char*)malloc(sizeof(char)*2)
cstr3 = (char*)malloc(sizeof(char)*6)
cstr1="test";
cstr2="ok";
cstr3="testing";
0001 t
0010 e
0011 s
0100 t
0101 o
0110 k
0111 t
1000 e
1001 s
1010 t
1011 i
1100 n
1101 g
1110
1111
Now if you were to free up cstr2, there would be a gap of 2 bytes between cstr1 and cstr2. If you were to attempt to create another array of characters, 4 bytes long, would the compiler shift the array holding 'testing' up two bytes, to fit in the new array, or would it simply generate an error?
Re: A question about memory allocation
well, first off the memory wouldn't look like that.
you're allocation memory, then assigning a pointer to a constant string, which is automatically stored elsewhere in memory.. not to mention the absence of null terminators.
i think i can answer the question though. i'm not 100% on what you intend to do, but if there are 2 bytes of free memory and you attempt to allocate 4, the program will look for the first space where there's 4 available bytes in a row. if you attempted to copy the contents of the array into that space, then yeah you would have a problem.
Re: A question about memory allocation
It depends on the malloc implementation.
In general, malloc uses a chain of pointers to available memory blocks. This is called the free chain. When you allocate memory, malloc walks the free chain looking for a chunk big enough. This is quite a primitive system.
So in principle, if you have at least 4 bytes free, you will be able to allocate a 4-byte block of memory. However, depending on how scattered the allocated blocks are, malloc may have to first clean up the free chain by re-arranging the currently allocated blocks of memory. This can take quite a long time, but you will get your 4 bytes.
An error will occur if you try to allocate more bytes than are available anywhere in the free chain.
Re: A question about memory allocation
ok, thanks for the answers guys =)
Re: A question about memory allocation
Quote:
Originally Posted by penagate
malloc may have to first clean up the free chain by re-arranging the currently allocated blocks of memory.
Um, it can't do that in C or C++, not on common implementations where pointers are direct memory addresses.
It can (and does) do it on hosted environments like the Java or .Net runtime.
Re: A question about memory allocation
Sorry, I meant the free blocks.