0

I have a very important question (for me)

How do i use <alloc.h>/<malloc.h>/<stdlib.h> for memory allocation?

i'm talking about: malloc(),calloc(),halloc(),realloc(),alloca(),heapwalk(),free()
etc?
i'm having a lot of trouble with these!

thank you!! :confused:

2
Contributors
2
Replies
7
Views
13 Years
Discussion Span
Last Post by Fili
0

These are used to allocate memory dynamically.With these you get memory from the OS and point to that memory address with a pointer.

Presonally I use C++ new operator.

Eg.

Some_data_type *object;

object = (Some_data_type*)malloc(sizeof(Some_data_type),1);

that is to assign memory.

Then when you are finished with it:

free(object);

That's the general way to use it.

0

Thx. I looked it up in a book.

BTW: Instead of using a vector: int a[100] you could use:

int *a;
a=(int*)malloc(100*sizeof(int)); OR
a=(int*)calloc(100,sizeof(int));

It's kind of useful. If you wanna read a vector of an undefined size (n), you have to aproximate and think within which intervals it is. If you use:

int n;
//reads the size
printf("n=");
scanf("%i",&n);
int *a=(int*)malloc(n*sizeof(int));

It's especially useful when you don't what to use up more memory than required! :D

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.