LinuxQuestions.org
Share your knowledge at the LQ Wiki.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 09-29-2004, 08:20 PM   #1
saiz66
Member
 
Registered: Apr 2003
Posts: 225

Rep: Reputation: 30
malloc in c programming


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?
 
Old 09-29-2004, 08:39 PM   #2
CroMagnon
Member
 
Registered: Sep 2004
Location: New Zealand
Distribution: Debian
Posts: 900

Rep: Reputation: 33
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.
 
Old 09-29-2004, 08:47 PM   #3
itsme86
Senior Member
 
Registered: Jan 2004
Location: Oregon, USA
Distribution: Slackware
Posts: 1,246

Rep: Reputation: 59
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).
 
Old 09-29-2004, 09:26 PM   #4
rustynailz
Member
 
Registered: Jun 2004
Distribution: MDK 9.2/10.0, VectorLinux 4.0
Posts: 50

Rep: Reputation: 15
Does the heap/stack model still apply in Linux?
 
Old 09-29-2004, 09:29 PM   #5
itsme86
Senior Member
 
Registered: Jan 2004
Location: Oregon, USA
Distribution: Slackware
Posts: 1,246

Rep: Reputation: 59
Quote:
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.
 
Old 09-30-2004, 04:58 AM   #6
Omarel
LQ Newbie
 
Registered: Nov 2003
Distribution: Slackware
Posts: 12

Rep: Reputation: 0
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?
 
Old 09-30-2004, 05:10 AM   #7
CroMagnon
Member
 
Registered: Sep 2004
Location: New Zealand
Distribution: Debian
Posts: 900

Rep: Reputation: 33
Dude, directly from the manpage:

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).
 
Old 09-30-2004, 09:35 AM   #8
itsme86
Senior Member
 
Registered: Jan 2004
Location: Oregon, USA
Distribution: Slackware
Posts: 1,246

Rep: Reputation: 59
Yeah, like CroMagnon pointed out, it's perfectly legal to use realloc() without malloc() or calloc() as long as the pointer you pass to it is NULL.
 
Old 09-30-2004, 10:10 AM   #9
llama_meme
Member
 
Registered: Nov 2001
Location: London, England
Distribution: Gentoo, FreeBSD
Posts: 590

Rep: Reputation: 30
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
 
Old 09-30-2004, 10:19 AM   #10
itsme86
Senior Member
 
Registered: Jan 2004
Location: Oregon, USA
Distribution: Slackware
Posts: 1,246

Rep: Reputation: 59
Quote:
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.
 
Old 10-01-2004, 04:40 PM   #11
Omarel
LQ Newbie
 
Registered: Nov 2003
Distribution: Slackware
Posts: 12

Rep: Reputation: 0
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.
 
Old 10-02-2004, 11:18 AM   #12
abdobl
LQ Newbie
 
Registered: Sep 2004
Location: Tripoli
Posts: 22

Rep: Reputation: 15
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..
 
Old 10-02-2004, 06:33 PM   #13
Omarel
LQ Newbie
 
Registered: Nov 2003
Distribution: Slackware
Posts: 12

Rep: Reputation: 0
Have you triend posting in the corect forum? Not programming one?
 
Old 10-02-2004, 07:01 PM   #14
aluser
Member
 
Registered: Mar 2004
Location: Massachusetts
Distribution: Debian
Posts: 557

Rep: Reputation: 43
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.
 
Old 10-03-2004, 12:18 PM   #15
Omarel
LQ Newbie
 
Registered: Nov 2003
Distribution: Slackware
Posts: 12

Rep: Reputation: 0
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.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
sizeof and malloc in C exvor Programming 4 08-07-2005 12:06 PM
malloc eagle683 Programming 6 05-22-2005 02:40 PM
malloc() vijeesh_ep Programming 4 08-25-2004 03:50 PM
malloc debugger legolas_t Programming 3 07-04-2004 01:32 PM
about malloc eshwar_ind Programming 11 02-18-2004 03:41 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 12:37 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration