Thread: is this right way to use malloc.

  1. #1
    Registered User
    Join Date
    Sep 2008
    Posts
    53

    is this right way to use malloc.

    i would like to ask if this is the right way to use malloc or if i am doing anything wrong.
    i just turned the page about structures a few days ago in the book i am using.
    thanks for the time to comment.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <errno.h>
    #include <string.h>
    
    struct contents
    {
    	int chars;
    	int digits;
    	int others;
    };
    void PrintUsage(const char *progname);
    int main(int argc, char** argv)
    {
    	int c;
    	int i;
    	int ch,digit,other;
    	    ch=digit=other=0;
    
    	FILE *fp;
    	
    	  if( argc == 1 )
    	  {
    		   PrintUsage(argv[0]);
    		   exit(EXIT_FAILURE);
    	  } 
    		  
    		  struct contents *count=malloc(sizeof(count));
    		  
    		  if(count == NULL)
    		  { 
    			 errno=EINVAL;
    			 perror(argv[0]);
    		        exit(1);
                     }
    		  
    		 for(i=1;i< argc;i++)
                   {
    	                if((fp=fopen(argv[i],"r")) == NULL)
    	                {
                                errno=EINVAL;
    		                    perror(argv[0]);
    	                        exit(EXIT_FAILURE);
    	                }
    
    	              while((c=fgetc(fp))!= EOF)
    	             {
    		             switch(c)
    		            {
    		            	  case '1':case '2':case '3':case '4':case '5':
    			              case '6':case '7':case '8':case '9':case '0':
    			              digit++;  
    				      count->digits++;
    			              case ' ': case '\n': case '\t':
    			              other++;
    				     count->others++;
    			              default:
    			              ch++;
    				     count->chars++;
    		            }
    
                 	}  
    	/* it prints total of the files if more than 1 file is counted. for now its considered a feature :) */
       fprintf(stdout,"nchar %d ndigit %d nother %d %s\n",ch,digit,other,argv[i]);
       fprintf(stdout,"nchar %d ndigit %d nohter %d %s\n",count->chars,count->digits,count->others,argv[i]);
    
              } /* end for loop*/
    		  
    	     fclose(fp);
    		free(count);
    	     count=NULL;
    	
    	return 0;
    }
    
    void PrintUsage(const char *progname)
    {
    	fprintf(stdout," usage: %s [file]              \n"
    	               "counts chars digits and others \n",progname);
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    This is not correct:
    Code:
    struct contents *count=malloc(sizeof(count));
    It should be:
    Code:
    struct contents *count = malloc(sizeof(*count));
    However, in this case it would be better not to use malloc at all since you do not need dynamic memory allocation.

    By the way, you need to indent more consistently. Perhaps you are mixing tabs and spaces?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    Also, you appear to be missing some break statements in your switch block. If you don't use break, each case will fall through to the next.
    bit∙hub [bit-huhb] n. A source and destination for information.

  4. #4
    Registered User
    Join Date
    Sep 2008
    Posts
    53
    thanks.

    i completely forgot the break statements. it was just a rather hello world like project i started out last night so i just posted what i got from before i went to bed.

    sorry the indent is a bit off. i fine tuned it before posting.

  5. #5
    Banned
    Join Date
    Aug 2009
    Posts
    43
    Quote Originally Posted by laserlight View Post
    This is not correct:
    Code:
    struct contents *count=malloc(sizeof(count));
    It should be:
    Code:
    struct contents *count = malloc(sizeof(*count));
    However, in this case it would be better not to use malloc at all since you do not need dynamic memory allocation.

    By the way, you need to indent more consistently. Perhaps you are mixing tabs and spaces?
    i dissagree
    it should be
    struct contents *count=malloc(sizeof(struct contents));

    count is just a variable its not a type

  6. #6
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    No, laserlight is correct. You can do sizeof with a variable just as well as a type. Using the variable has the added benefit that if you ever change the variable type, the code still works as is.

    For example:
    Code:
    char* var = malloc(sizeof(char));
    vs
    char* var = malloc(sizeof(*var));
    // If you ever change the type of var from char to int, you do not need to change what gets passed to malloc()
    bit∙hub [bit-huhb] n. A source and destination for information.

  7. #7
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by kakaroto
    i dissagree
    it should be
    struct contents *count=malloc(sizeof(struct contents));
    That is certainly one way of doing it, but it has the disadvantage that if the type of count is changed, the update has to be made in two places, and it can be the case that failure to do so results in a run time error (or no error at all, until further down the road after maintenance).

    Quote Originally Posted by kakaroto
    count is just a variable its not a type
    Yes, and sizeof(*count) results in the size of an object that count would point to.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  8. #8
    Banned
    Join Date
    Aug 2009
    Posts
    43
    ahhhh aint that the coolest thing

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc + segmentation fault
    By ch4 in forum C Programming
    Replies: 5
    Last Post: 04-07-2009, 03:46 PM
  2. Is there a limit on the number of malloc calls ?
    By krissy in forum Windows Programming
    Replies: 3
    Last Post: 03-19-2006, 12:26 PM
  3. Malloc and calloc problem!!
    By xxhimanshu in forum C Programming
    Replies: 19
    Last Post: 08-10-2005, 05:37 AM
  4. malloc and realloc
    By odysseus.lost in forum C Programming
    Replies: 3
    Last Post: 05-27-2005, 08:44 AM
  5. malloc() & address allocation
    By santechz in forum C Programming
    Replies: 6
    Last Post: 03-21-2005, 09:08 AM