I want to allocate a big memory location, up to 4kb, and want it to be dynamic. However, I don't know how. Please help me! Thank you very much any help.
I want to allocate a big memory location, up to 4kb, and want it to be dynamic. However, I don't know how. Please help me! Thank you very much any help.
>I want to allocate a big memory location, up to 4kb, and want it to be dynamic.
Just 4kb?
-PreludeCode:T *mem = malloc ( sizeof *mem * 4096 );
Last edited by Prelude; 10-08-2002 at 10:44 AM.
My best code is written with the delete key.
Hi Prelude,
Thanks! What is T?
>Thanks! What is T?
The data type of the block of memory you want to allocate. You didn't specify, so I used the generic notation T which means "Your data type here".
-Prelude
My best code is written with the delete key.
O.k. Thanks you guys. I got it.
Don't forget to free the memory when you don't need it anymore.
free (mem);
Using type of void
you can change it to other types in future..
Isn't it possible Salem?
[ Never code before desk work ]
-------------------------------------:-->
A man who fears Nothing is the man who Loves Nothing
If you Love Nothing, what joy is there in your life.
=------------------------------------------------------= - I may be wrong.
I answered this same question for the same person in another thread. *mutter* Anyway, they asked how to allocate 4KB, not how to allocate four thousand integers, characters etc.Originally posted by Prelude
>I want to allocate a big memory location, up to 4kb, and want it to be dynamic.
Just 4kb?
-PreludeCode:T *mem = malloc ( sizeof *mem * 4096 );
So to be picky, this would be the preferred method, since it would give you exactly 4KB:
T *mem = malloc( 4096 );
Quzah.
Hope is the first step on the road to disappointment.
You can also do allocations using a function called calloc() which allocates a zeroed out memory buffer.
For instance
could also be done like thisCode://i don't care what ppl say I still type cast int *mem = (int *)malloc(50 * sizeof(int));
The only difference is that calloc would make every byte in the array a zero whereas malloc leaves you with random values.Code:int *mem = (int *)calloc(50, sizeof(int));
Hi,
Just out of intrest what happens if you dont free memory allocated in a program. I thought that the OS frees all resources given to a program on exit. So by this logic it would be ok not to free memory.
I know this is bad thinking but suddenly realised that I dont know why?
Brif
>I thought that the OS frees all resources given to a program on exit.
Most do, but you can't be sure of this. My system will free resources after my program exits, but it will usually do so slowly so if I allocate huge amounts of memory, the computer will run sluggishly for about ten minutes after my program ends. It's best to assume that your system will not reclaim memory and clean up after yourself.
-Prelude
My best code is written with the delete key.
Thanks Prelude,
youve sent me on the first steps to enlightenment,
brif