When to use Malloc?


 
Thread Tools Search this Thread
Top Forums Programming When to use Malloc?
# 1  
Old 10-15-2005
When to use Malloc?

Hi!
I hope this is the correct forum to post the question even if I'm a newbie...
I am a C-newbie (and really on the edge to be a C-addict Smilie ) and have a question.

When should I use malloc?
To state it differently, when should I NOT use malloc?

For instance, if I have an array of chararray/string pointers . Should I allocate space for both the array AND the strings?

Thank you for reading my question. Smilie This really has been bugging me lately... Smilie
Tonje
# 2  
Old 10-16-2005
The decision of whether to use malloc or not really depends on you.

If you want to have a program that does not allocate space that it does not need, then you should use malloc to allocate space when you know how much you will need. Also, if you are expecting to allocate a very large array, say of 100000 bytes or something, but it is possible that some cases may have only 500 of those bytes actually used, then you are again better off using malloc to allocate just those many bytes.

Of course, if you are going to use malloc - especially in a loop, remember to use free, or you risk crashing your program.
# 3  
Old 10-16-2005
Thank you for replying so quickly! Smilie

When I do not know the maximum size of the strings, it just seems like a waste of time to first count the letters then to malloc sufficiant space for the string.
But then again, I guess one gets better contol over the program?

What actually happens if I don't malloc space for the strings, (in the situation as mentioned in my previous post), and the strings that the array points to change all the time. What about the space the old strings occupy, will that automaticly be free space, or will it be occupied until the program terminates?

Thanks a million for your answer! Smilie

Tonje
# 4  
Old 10-17-2005
Quote:
What actually happens if I don't malloc space for the strings, (in the situation as mentioned in my previous post), and the strings that the array points to change all the time. What about the space the old strings occupy, will that automaticly be free space, or will it be occupied until the program terminates?
I really haven't got your question, but will try to answer just the same,
If you declare a character array for strings like char a[50], then you can have the string that occupies it change frequently over the course of your program, but as long as it does not go over 50*sizeo(char) bytes, it wont matter. The space that the old string occupies will be overwritten by the new one.
Note that the question of freeing space does not come up, as you have statically allocated memory. It will be freed only when you exit the program.

--NOTE--
The use of the word 'statically' does not mean that you are declaring any of the variables as static.
Code:
static int a;

is different from
Code:
 int a;

--/NOTE--

Last edited by blowtorch; 10-17-2005 at 10:58 AM.. Reason: fix broken tag
# 5  
Old 10-17-2005
Thank you very much for your reply. It is "clearer" for me now. Smilie)
# 6  
Old 10-17-2005
The advantages of malloc
1. unix limits stack space - where normal C variables are stored.
malloc uses heap memory which is usually not as limited as stack memory.
2. after you call malloc, you can re-size storage for your buffer with realloc.
you can make it larger or smaller. So you do not have to worry about
sizing your variables to gigantic proportions beforehand.

Reading a whole file example:
Code:
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/stat.h>
#include <string.h>

#define ck(x) if((x)==NULL)\
{perror("Error"); exit(EXIT_FAILURE);}
/* read nbyte from a file  - can read whole file */
ssize_t readall(int fd, void *buf, size_t nbyte){
     ssize_t nread = 0,
                   n=0;

     do {
         if ((n = read(fd, &((char *)buf)[nread], nbyte - nread)) == -1) {
             if (errno == EINTR)
                 continue;
             else
                 return (-1);
         }
         if (n == 0)
             return nread;
         nread += n;
     } while (nread < nbyte);
     return nread;
}

 /* get file size */
size_t file_size(FILE *in)
{
	 struct stat st;
	 if(fstat(fileno(in), &st) == (-1))
	 {
	 	perror("stat error");
	 	exit(EXIT_FAILURE);
	 }	
     return st.st_size;
}

int main(int argc, char *argv[1])
{
	char *buf=NULL;
	FILE *in=fopen(argv[1],"r");    /* open afile for read */
	size_t filebytes=0;

	ck(in);                       /* check file errors */
	filebytes=file_size(in);      /* get size of buf we need */
	if(filebytes)                 /* do we have a file with data in it? */
	{
		ck(buf=malloc(filebytes+1) );	/* create storage */
		memset(buf,0x0, filebytes+1);   /* init storage */
		if( readall(fileno(in),buf,filebytes)>0 ) /* read entire file */
		{
			ck(fprintf(stdout,"%s",buf)); /* print whole file */
		}
		else                         /* complain about errors reading file */
		{
			ck(fprintf(stderr,"file read error\n") );
			exit(EXIT_FAILURE);
	    }
	    free(buf);                 /* release the buffer */
	}
	if(! fclose(in)	)              /* close file with error check */
    {
    	return 0;                  /* normal return */
    }
	ck(fprintf(stderr, "filesystem error\n") );
	return EXIT_FAILURE;           /* file close error - return */
}

Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Dummies Questions & Answers

Help with malloc()

Good day! I'm a newbie in C. I'm trying to get an unlimited input from the user using malloc then printing the inputs after the user presses enter. My code works, but there's a warning that I don't know how to fix. Please help me. Thank you. Here's my code: #include <stdio.h> #include... (6 Replies)
Discussion started by: eracav
6 Replies

2. Programming

malloc vs new speed

Which one is faster among malloc and new? My understanding is that since new also has to call constructors after allocating memory it must be slower than malloc. Am I correct? (1 Reply)
Discussion started by: rupeshkp728
1 Replies

3. Programming

help with malloc [solved]

Hi i found code in google how to malloc an 2D array and i tried that : #include<stdio.h> #include<stdlib.h> int **A; int **B; int main(int argc,char *argv) { printf("name of text : %s\n",argv); //read arrays int i,j; int l,m; int M,n; FILE *fp; fp=fopen(argv,"r"); ... (0 Replies)
Discussion started by: giampoul
0 Replies

4. UNIX for Dummies Questions & Answers

Kmalloc and malloc

Do kmalloc and malloc allocate from same heap ? (3 Replies)
Discussion started by: dragonpoint
3 Replies

5. Programming

malloc vs realloc

Why when using realloc, john is reversed 3 times but not the other 2 names ? But if I use malloc, then the 3 names are reversed correctly ? (but then there is a memory leak) How can I reverse all 3 names without a memory leak ? char *BUFFER = NULL; char *STRREVERSE(const char *STRING) {... (5 Replies)
Discussion started by: cyler
5 Replies

6. UNIX for Advanced & Expert Users

Malloc Implementation in C

Hey Guys Some of my friends have got together and we are trying to write a basic kernel similar to Linux. I am trying to implement the malloc function in C and I am using a doubly linked list as the primary data structure. I need to allocate memory for this link list (duh...) and I don't feel... (2 Replies)
Discussion started by: rbansal2
2 Replies

7. Programming

Malloc implementation in C

Hey Guys I am trying to implement the malloc function for my OS class and I am having a little trouble with it. I would be really grateful if I could get some hints on this problem. So I am using a doubly-linked list as my data structure and I have to allocate memory for it (duh...). The... (1 Reply)
Discussion started by: Gambit_b
1 Replies

8. Programming

malloc()

Some one please explain me what is Dynamic memory allocation and the use of malloc() function.How do we allocate memory dynamically and also the other way? (3 Replies)
Discussion started by: rash123
3 Replies

9. Programming

malloc

hello sir since by mentioning a integer pointer and storing the integers by incrementing the pointer value then what is the purpose of malloc? u can decalre it as in t *p; several integers can be stored by incrementing the value of p, hence what is the diffrence between this... (2 Replies)
Discussion started by: rajashekaran
2 Replies

10. Programming

a problem about malloc()

1 . Thanks everyone who read the post. 2 . the programe is that : #include <stdio.h> #include <string.h> void do_it(char *p) { p = (char *) malloc(100); (void )strcpy(p,"1234"); } int main(void) { char *p; do_it(p); (void )printf("p = %s \n",p); (1 Reply)
Discussion started by: chenhao_no1
1 Replies
Login or Register to Ask a Question