Thread: Most Common problems in C

  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

  2. #2
    Registered User
    Join Date
    Oct 2008
    Posts
    1,262
    Nice post. But you forgot the single most common:
    "My homework is due tomorrow please make it for me"

  3. #3
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    Your intention is nice but don't forget that the ignorance of posters that EVOEx describes above is greater than any FAQ, or compilation of issues you can come up with. All of these issues are addressed on the FAQ, there are numerous stickies and pointers when you register as to read them however, they are ignored. I am afraid your post will suffer the same treatment unfortunately.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  4. #4
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    That is a pretty good list. Altho it's not C specific, I'd add the "off by one" (aka, fencepost) errors:

    Off-by-one error - Wikipedia, the free encyclopedia

    which are very easy for beginners in particular to make. Having a name for this one (OBOE or fencepost) is good because once you know the name it is more likely to occur to you as a possibility where appropriate (or at least spot once it's happened). There are some common C specific situations involving the null terminator on strings -- eg:
    Code:
    char *copy = malloc(strlen(string));
    strcpy(copy,string);
    Off by one overflow!

    Quote Originally Posted by claudiu View Post
    I am afraid your post will suffer the same treatment unfortunately.
    Maybe, but Bayint Naung has hit on some very common issues that probably cannot be repeated too many times. It would not be a bad idea to refer to someone who has made one of them to a "top 10" list the first time. For every person that ignores that kind of thing, I bet there are more that actually take an interest and even learn something -- just you won't be hearing from them.
    Last edited by MK27; 06-02-2010 at 06:22 AM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  5. #5
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    @ MK27, I forgot that! How to avoid Off by One error?! Count carefully?

  6. #6
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by Bayint Naung View Post
    @ MK27, I forgot that! How to avoid Off by One error?! Count carefully?
    I guess. I would say that for allocation, too much is better than too little, but that is not true for iterative reads, so not very good advice. Seems to me that once I read the analogy (you need 11, not 10 fenceposts for a 100' fence with posts every 10 feet) it was easier to conceive of and notice.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  7. #7
    Registered User
    Join Date
    Oct 2008
    Posts
    1,262
    Quote Originally Posted by MK27 View Post
    I guess. I would say that for allocation, too much is better than too little, but that is not true for iterative reads, so not very good advice. Seems to me that once I read the analogy (you need 11, not 10 fenceposts for a 100' fence with posts every 10 feet) it was easier to conceive of and notice.
    I find your analogy off for your own example. While this can be, indeed, the cause for off-by-one errors, it's not for the copying of strings. That is not caused by forgetting to add one after subtraction, but rather by forgetting to count \0 as a character that has to be stored as well. Still an off by one error, but different analogy.

  8. #8
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by EVOEx View Post
    I find your analogy off for your own example.
    Technically, I wasn't using that analogy with that example, they were in two separate posts.

    You're right, tho, understanding the fencepost error may or may not help with the strlen one in the strict sense of the fencepost analogy being about inclusion in a series (0-10 is eleven numbers).

    On the other hand, it is still conceptually similar -- when you get to the tenth pole, you'll notice there's still a unit of fence left unaccounted for, altho in this case it has to do with a C specific issue (what strlen counts and what a C string is) as opposed to a plain old arithmetic error.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  9. #9
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    Well, fueled by MK27's relentless optimism I decided it's time to drop the skepticism and add my own thing here. One thing I see here everyday and is driving me nutz, although not a mistake per say is the casting of malloc().

    Another thing, which is not necessarily related to C is the confusion between an IDE and a compiler. Most people will come and say... "ohh I compilez my codez with Eclipse and needz helpz cuz deadline iz tomorrow!".
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  10. #10
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    It's not really an error to cast mallocs return type, it's just unnecessary in C.
    Last edited by Subsonics; 06-02-2010 at 10:05 AM.

  11. #11
    Registered User
    Join Date
    Mar 2008
    Posts
    82
    claudiu you must'nt have any hair left, because casting malloc seems to be the dominant style in alot of code I, at least, need to analyse.

    Hell, I even do it, so nobody looks askance at my code.

    The confidence to not cast your mallocs, must be the sign of an advanced coder, I reckon.

    Of course people say, "oh, it's just to make my code clearer", oh yeah, right .. the logic being "if I cast my mallocs, I can claim to write clear code, the rest can remain unclear"

  12. #12
    Registered User
    Join Date
    Mar 2009
    Posts
    344
    How about "if (x == 5 || 6) " instead of if (x == 5 || x == 6)or similar misunderstandings of logical operators? A variant would be something like "if (0 <= x <= 10)" for people more familiar with math than C syntax.

  13. #13
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    Quote Originally Posted by stabu View Post
    claudiu you must'nt have any hair left, because casting malloc seems to be the dominant style in alot of code I, at least, need to analyse.

    Hell, I even do it, so nobody looks askance at my code.

    The confidence to not cast your mallocs, must be the sign of an advanced coder, I reckon.

    Of course people say, "oh, it's just to make my code clearer", oh yeah, right .. the logic being "if I cast my mallocs, I can claim to write clear code, the rest can remain unclear"
    As the poster above mentioned casting malloc in C is not a problem of confidence. It is totally useless. In fact, it can even prove dangerous if you don't include stdlib because then the function will be assumed to return an int. If ints and pointers are of different sizes on your machine, you may be in for a run-time surprise. The code you are looking at is probably compiled with a C++ compiler. I feel like most people compiling with gcc or other C compilers cast malloc BECAUSE they don't really understand the reason why they don't need to cast it.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  14. #14
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Let me add something:
    Considering that your posts cannot be edited after some time, and that noone wants to read through a thread with 1000X posts, and read lots of replies that aren't relevant to them, how about just summarizing it all in a page that has already begun? Like, for example, SourceForge.net: Common mistakes and errors - cpwiki?
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  15. #15
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    I cast mallocs because my C++ compiler, when Warning level is 4 (I think), would complain about mismatched type otherwise. I see no problem with casting malloc... as long as its prototype is included of course and it's not defaulting to int as mentioned above.

    More common C problems encountered:

    Semicolon follows "for" statement immediately... thereby making an empty loop. Hard to spot for newbies but I've seen this issue a few times now.

    Confusion about int, long, long long and their maximum values allowable. Also difference between float and double, and corresponding formatting parameters for scanf, printf, etc.

    Prudent use of global variables where needed. Review of stacked variables (are they called volatile, officially?) vs. use of the keyword "static".

    Something a bit more general: lack of understanding of what "binary" file really is. I hate the term myself since every file (in fact everything) is binary anyhow. So let's reacquaint students with what "printable characters" are, new-line characters, etc. Just like back in the day we learned the ASCII chart.

    Not strictly C but related: how to navigate through a directory/folder to access files. This problem seems to pop up often.

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