Sponsored Content
Full Discussion: When to use Malloc?
Top Forums Programming When to use Malloc? Post 86776 by jim mcnamara on Monday 17th of October 2005 10:14:32 AM
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 */
}

 

10 More Discussions You Might Find Interesting

1. 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

2. 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

3. 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

4. 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

5. 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

6. 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

7. UNIX for Dummies Questions & Answers

Kmalloc and malloc

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

8. 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

9. 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

10. 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
All times are GMT -4. The time now is 12:49 AM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy