Thread: Most Common problems in C

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314

    Most Common problems in C

    I'd like to make a list of most common problems that newbies to C are facing and possible solutions.
    I'll start with:

    Problems

    1. fflush(stdin)
    2. scanf() leaves newline ( related to 1 )
    3. void main(void) vs int main(void)
    4. not initializing variable before use
    5. pointer vs array
    6. scanf("%s",&array_name) ;
    7. misplacing equality operator( == ) with assignment operator (=)
    Code:
        if( i   =   1 )   {       /* trouble! */ 
         if( 0 < n < 10 )  instead of if( n > 0 && n < 10)
         if (x == 5 || 6)  instead of  if (x == 5 || x == 6)
    8. Off by One Error ( by Mk27)
    Code:
     
         char *copy = malloc(strlen(string));       /* forget +1 for null char*/
         strcpy(copy,string);
    9.
    Code:
      
           foo_t *p;
    
           p = malloc( sizeof(*p) );          // good practice 
           
           p = malloc( sizeof(foo_t) );
    Solutions

    1. fflush(stdin)
    2. same as 1
    3. void main(void) vs int main(void)
    4. Enable compiler warning (for gcc, use -Wall flag)
    5. pointer vs array
    6. scanf("%s",&array_name);
    7. Enable compiler warning.
    8.
    9. The former method is less accident prone, and is easier to maintain (ie: you don't have to ever change it). If you go back and substitute foo_t for bar_t, you have to chase down all of your malloc calls, and change them too. If you use the first method, you don't have to. ( By quzah )

    Please feel free to add other problems you could think of.
    Last edited by Bayint Naung; 06-02-2010 at 08:57 PM. Reason: Grammar error

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to handle multiple cases which use common code?
    By tmaxx in forum C Programming
    Replies: 3
    Last Post: 10-03-2008, 07:42 AM
  2. common functions
    By FoodDude in forum C++ Programming
    Replies: 3
    Last Post: 09-22-2005, 02:13 PM
  3. Common Problems
    By WolfPack in forum C Programming
    Replies: 4
    Last Post: 01-28-2003, 06:38 PM
  4. Lowest Common Factor
    By PJYelton in forum C++ Programming
    Replies: 9
    Last Post: 12-23-2002, 09:30 AM
  5. Coding Problems
    By RpiMatty in forum C++ Programming
    Replies: 12
    Last Post: 01-06-2002, 02:47 AM