ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Hi. I am learning c programming and I am a kind of confused bout the use of malloc. Could somebody please explain to me what malloc does and how it should be used properly and to know when to use it?
malloc is used to allocate memory (m-alloc) at runtime. For example, when you don't know how much storage you will need beforehand. Say if you wanted to load a file into RAM, you might check how many bytes the file takes up, call malloc for that amount, and get back a pointer to a buffer of that size. That's about as much as I know, not being a C programmer, except that you should always check the return value in case the memory couldn't be allocated, and you should always free the memory once you're done with it. Oh, and remember that the memory is not cleared, so there's no guarantee as to what you might find in it. If you want guaranteed zero bytes, use calloc instead.
You use it when you don't know how much data you'll need to be storing. For instance, let's say you're asking a user for a list of student test scores. You might go with this approach:
Code:
#include <stdio.h>
#include <stdlib.h>
#define MAX_SCORES 25
int main(void)
{
char buf[50];
float scores[MAX_SCORES];
int i;
puts("Enter student scores. Press ENTER with no value to finish.");
for(i = 0;i < MAX_SCORES;++i)
{
printf("Enter student %d's score: ", i+1);
fflush(stdout);
fgets(buf, sizeof(buf), stdin); // fgets() pulls the \n from stdin
if(*buf == '\n')
break;
scores[i] = atof(buf);
}
return 0;
}
But you notice that if the teacher wants to type in more than 25 scores she's kinda screwed. You can always raise MAX_SCORES to something higher, but when is it enough? This is where dynamic memory allocation comes in. Here's another example of the same program, but with the ability to let the teach enter as many scores as she wants:
Code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char buf[50];
float *scores = NULL, *tempptr;
int i;
puts("Enter student scores. Press ENTER with no value to finish.");
for(i = 0;;++i)
{
printf("Enter student %d's score: ", i+1);
fflush(stdout);
fgets(buf, sizeof(buf), stdin); // fgets() pulls the \n from stdin
if(*buf == '\n')
break;
tempptr = realloc(scores, sizeof(float)*(i+1));
if(tempptr == NULL)
{
puts("Unable to accept any further scores. Processing entered scores");
break;
}
scores = tempptr;
scores[i] = atof(buf);
}
free(scores);
return 0;
}
Now the teacher can enter as many scores as she wants (until her PC runs out of memory).
Originally posted by rustynailz Does the heap/stack model still apply in Linux?
Indeed it does. malloc(), realloc(), calloc(), and free() all have to do with the heap. There's a non-standard function called alloca() that is designed to allocate memory from the stack, but its usage is discouraged.
itsme86, I am really curious... It's corect to call realloc without calling malloc first? Because I've been always using first of all malloc and after this realloc. I mean the program shouldn't allocate first memory at some specific adress and after this relloc will alocate the memory starting with the same point? If you are using directly realloc how do you know in which point to alocate the memory?
realloc() changes the size of the memory block pointed to by ptr to size bytes. The contents will be unchanged to the minimum of the old and new sizes; newly allocated memory will be uninitialized. If ptr is NULL, the call is equivalent to malloc(size); if size is equal to zero, the call is equivalent to free(ptr).
Using realloc is usually a bad idea because it's a very inefficient way of extending an array. You might want to try using another data structure (e.g. a linked list) instead.
Originally posted by llama_meme Using realloc is usually a bad idea because it's a very inefficient way of extending an array. You might want to try using another data structure (e.g. a linked list) instead.
Alex
A linked list is a bit of overkill in this application. It's not like the array is being rapidly extended. It's waiting for user input each time. I can guarantee you that the user will never be able to tell that realloc() is even being called.
From the things I know, the best way to enlarge an array is with realloc. Using linked lits you're waisting a lot of memory for each member of the list (because you are making a structure for the list write? So for each member you are using the memory for one pointer, that I agree is very small but what if you have 1000 infos? ). And realloc is working very good. I just wasn't sure about using realloc w/o using malloc. But now I understood, thx.
Hi every body ....
I am facing a problem that gets me crazy,I have tow machines running redhat 9, tcpserver and tcpclient,when the server sends the date (about 40000Bytes) ,the client does not recieve all the data(it recieves only 361 Bytes,the rest are =0.0),I never understood that,
any help will be appresiated.
my regards,abdobl..
Omarel: realloc() often copies the entire contents of your array into a new, larger array. So in order to use realloc your system needs to (temporarily) provide double the memory you're using for the array, not to mention do the expensive copy operation. This is why people recommended a linked list -- there is no efficient way to extend an array. (Ok, sometimes realloc() may find free memory directly after the end of your array, in which case the extension is cheap, but this isn't generally true.)
Obviously, for this application there's no way you'll ever notice the performance difference so realloc() makes sense because it's easier to use.
U will may be right aluser. Actually I haven't made any very complex program in that I can tell the difference, the true is that I like linked lists very much also, but I've never seen them as an expandable array untill this moment, and the thing is that now that you are telling me this u are probably very right. I was using lists only for complex structures, like stundents marks, names, etc... not for just simple arrays .
But still is one problem: using linked lists you are using smth like:
typedef struct st{
int val;
st *next;
}array;
So you are using anyway more memory than a simple array... of course u are right that not so much as double of the array but anyway still using memory. That's why I like more realloc for simple arrays.. because as u said it's just temporarly memory used.. memory that will be freed after the use of realloc while in linked list u are not deleting the memory used by the pointers u are using... let's say is a big number of items.
Anyway as I told you I never tried with some complex aplication so I am very sure that u may be right (supposing u are much more experienced than me). I am still a student.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.