954,135 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How to use alloc's memory allocation functions?

I have a very important question (for me)

How do i use // 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:

Fili
Light Poster
34 posts since Jun 2004
Reputation Points: 16
Solved Threads: 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.

FireNet
Posting Whiz in Training
258 posts since May 2004
Reputation Points: 108
Solved Threads: 7
 

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

Fili
Light Poster
34 posts since Jun 2004
Reputation Points: 16
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You