Question:
C programming using malloc?
bill k
2012-10-04 16:54:01 UTC
Hello. What is malloc? I know it stands for memory allocation. But what is the point of it and how would I use it? Please give a couple of really simple examples a beginner would understand. Is it really necessary to reserve memory nowadays when 1GB+ is normal in everyday PCs? Short C program examples will definitely help.
Five answers:
Jonathan
2012-10-04 17:38:30 UTC
I guess there is a technical question and a big picture question here. Big picture, one could just allocate everything you might ever need as static variables which simply exist so long as the program exists. And your note about gigabytes of RAM certainly suggests that a simple "allocation of everything at compile time" could work for programs where it would not work so well 30 years ago. But there are a lot of good technical reasons for malloc(), just the same. But on a kind of big picture level the reason is that (1) programs may be able to handle a wider array of circumstances and (2) operating systems will almost certainly work better when there are lots of programs kept running or available. Used to be you just ran one program at a time, perhaps a sequence of them in a "batch." Today, workstations let you copy and paste and keep lots of programs, drivers, background routines, and these often cooperate with each other in novel ways that perhaps even the programmers themselves hadn't considered. So it's a good idea on that level.



The technical side is more of a "lifetime" thing. In C, (1) variables may exist for the duration of a local function's lifetime (local lifetime variables); (2) may exist all the time the program exists and is running (static lifetime variables, which are either defined at module level or else are defined within a function but using 'static' as a keyword); and (3) may exist for a period of time longer than a function itself, but shorter than the entire program life -- these are the 'heap' variables and they are allocated using malloc. A function using malloc can allocate some memory and return a pointer to it, allowing some other routine to decide when to destroy it later on. There is value in that even with gigabytes of memory.



Microsoft's Word program creates a document instance when you create a new document. It can't do that as a local function variable -- as soon as the function exits, it's gone. It could do that as some large, but mostly unused static lifetime array of the maximum number of documents you are allowed to open. But then the program memory footprint would be huge, making some of its management by the operating system a little more difficult. And most of the time far, far less would be needed anyway. So why pressure the memory system (or the page file on disk?)



I'm not sure what kind of short example program would help you here. All it would do is pony up some idealized (and not practical) example that would make no point by itself.
Techwing
2012-10-04 17:44:42 UTC
It is always necessary to reserve memory, no matter how much is available. The only question is whether to reserve it when the program is written, or after the program starts running.



The ordinary declaration of variables outside function scope allocates memory at compile time. The malloc() function allocates memory dynamically at run time.



The malloc() function is used when the exact memory requirements of a program are not known at the time it is written. The program can determine what it needs after it starts running and then call malloc() to actually obtain the needed memory.



Here's an example, a program that lets you store a variable number of integers:



#include

using namespace std;



int main(int iArgs, char *pszArgs[])

{

int Amount, *Integers;

cout << "How many integers do you need to store? ";

cin >> Amount;

Integers= (int*) malloc(sizeof(int)*Amount);

if (Integers==NULL)

{

cout << "Memory allocation failed!";

return 0;

}

for (int *Work=Integers, Index=1; Index<=Amount; Index++)

{

cout << "Enter integer " << Index << ": ";

cin >> *Work;

Work++;

}

for (int *Work=Integers, Index=1; Index<=Amount; Index++)

{

cout << "Integer " << Index << " is " << *Work << endl;

Work++;

}

free(Integers);

return 0;

}
anonymous
2012-10-04 17:45:35 UTC
malloc Allocates a block of size bytes of memory, returning a pointer to the beginning of the block. The content of the newly allocated block of memory is not initialized, remaining with indeterminate values.



It should have a sizeof parameter , Size of the memory block, in bytes.



On success, a pointer to the memory block allocated by the function. The type of this pointer is always void*, which can be cast to the desired type of data pointer in order to be dereferenceable. If the function failed to allocate the requested block of memory, a null pointer is returned.
gum
2016-07-29 06:19:27 UTC
I agree with the primary answerer. Why use char **buffer? Try it with one asterik. Additionally, add 1 more byte to the malloc to go away room for the null personality. Char *buffer = NULL; fgets(line, BUFSIZE, fp); lengthOfLine = strlen(line); buffer = (char*)malloc(lengthOfLine + 1); strcpy(buffer, line);
anonymous
2012-10-04 17:33:56 UTC
you use malloc when you aren't sure you will need to allocate memory or you aren't sure how much you will need.



Use malloc for a linked list and reading in data from a file. This is not real code of course, but maybe something like this:



struct data

{

int id;

char LastName[MaxLength];

char FirstName[MaxLegnth];

int streeNumber;

char StreetName[MaxLegnth];

....

struct data *next;

}



int main()

{



struct data in;

struct data*root, *current



FILE * fp;

openDataFile("filename.dat",&fp);



while(readFileData(fp , &in))

{

current->next = (struct data *)malloc(sizeof(structdata));

(*current->next)=in;

current = current->next;

current->next = NULL;

}



..

.

.}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...