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:

Recommended Answers

All 2 Replies

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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.