dikidera
dikidera

Reputation: 2043

How do I use malloc properly?

Let's assume that I have a char variable that is going to hold 1000 bytes.

char var[1000];

How would I use malloc to allocate that much memory for whatever is going to be in there?

I've tried reading up on malloc, but even K&R did not seem to have much info on it.

Upvotes: 1

Views: 7487

Answers (5)

Some programmer dude
Some programmer dude

Reputation: 409136

There should be millions of pages explaining the use of malloc, I doubt you did much searching. But here is how you call it:

char *var = malloc(sizeof(char) * 1000);

For other types, just change it:

int *int_var = malloc(sizeof(int) * 1000);

Edit Remember that you have to free the allocated memory after use! Or you will have a memory leak.

free(var);
free(int_var);

Upvotes: 6

Alexander
Alexander

Reputation: 48232

If you have char var[1000] you do not need malloc this definition allocates 1000*sizeof(char) for your var so you can do something like var[999] = 'x';

Upvotes: 0

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143061

You do not want to use malloc for this variable, because it's already allocated, but you may achieve similar results by using

char *var = malloc(sizeof(char[1000]));
// do stuff
free(var);

Upvotes: 2

Constantinius
Constantinius

Reputation: 35039

If you have declared your variable as char var[1000]; you already have statically allocated that much memory. You don't need to call malloc for this.

If you want to use dynamic allocation and your variable is declared like this: char *var; you can allocate the memory as follows:

var = malloc(1000);

also don't forget to free your allocated memory when you're done with it:

free(var);

Upvotes: 0

mah
mah

Reputation: 39797

http://www.manpagez.com/man/3/malloc/

char *pVar = malloc(1000);
.... use pVar ....
free(pVar);
// DONT use pVar anymore

Upvotes: 0

Related Questions