Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
1K views

Common C Programming Errors

This document discusses common C programming errors including syntax errors, logical errors, string errors, and other issues. It provides examples of errors like missing semicolons, incorrect use of assignment vs equality operators, uninitialized pointers, not null-terminating strings, and more. The goal is to help programmers avoid these common mistakes by familiarizing themselves with the types of errors that occur frequently in C code.

Uploaded by

kokoizkaone
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
1K views

Common C Programming Errors

This document discusses common C programming errors including syntax errors, logical errors, string errors, and other issues. It provides examples of errors like missing semicolons, incorrect use of assignment vs equality operators, uninitialized pointers, not null-terminating strings, and more. The goal is to help programmers avoid these common mistakes by familiarizing themselves with the types of errors that occur frequently in C code.

Uploaded by

kokoizkaone
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Common C Programming Errors

Introduction
Incomputing,C is a general purpose
programming languageinitially developed
byDennis Ritchiebetween 1969 and 1973
atAT&T Bell Labs.
C is animperative(procedural) language. It was
designed to be compiled using a relatively
straightforwardcompiler, to provide low-level
access to memory and to require minimalruntime support. C was therefore useful for many
applications that had formerly been coded in
assembly language, such as insystem
programming. Like mostimperative
languagesin theALGOLtradition, C has
facilities forstructured programmingand
allowslexical variable scopeandrecursion.
C is one of the most widely used programming
languages of all time,and C compilers are
available for the majority of available computer
architectures andoperating systems.

Becoming familiar with common


errors not only improves
programming skills but it also saves a
lot of time.

Syntax Errors
The set of rules (grammatical rules) of aprogramming language for
writing statements of thecomputer programis known as syntax ofthe
language. The program statements are written strictly according to these
rules.
Syntax error occur when syntax of aprogramming languageare not
followed in writing thesource code. The compiler detects these errors at
compiling time ofsource code. The compiler reports a propererror
message about the error.
The compiler does not compile a program that contain syntax errors.
Thesyntaxerrors are easy to detect and remove.
In C program, there can be many causes of syntax errors.
Someexamplesare given below:Missing semicolon (;) at the end of statement.
Missing any of delimiters e.g.{or}
Incorrect spelling of any keyword.
Using variable without declaration etc.

Forgetting to put a break in a


switch statement
Remember that C does not break out of
aswitchstatementif acaseis
encountered. For example:
int x = 2;
switch(x) {
case 2: printf("Two\n");
case 3: printf("Three\n");
}

prints out:
Two
Three

If we put abreakto break out of theswitch:


int x = 2;
switch(x) {
case 2: printf("Two\n"); break;
case 3: printf("Three\n"); break;
}

prints out:
Two

In case 3 break is not necessary, but good if


additional cases are added later.

Using = instead of ==
C's=operator is used exclusively for assignment and returns the value
assigned. The==operator is used exclusively for comparison and returns an
integer value (0 forfalse, not 0 fortrue). Because of these return values, the C
compiler often does not flag an error when=is used when one really wanted
an==. For example:

int x = 5;
if ( x = 6 ) printf("x equals 6\n");
This code prints outx equals 6! The assignment inside theifsetsxto 6
and returns the value 6 to theif. Since 6 is not 0, this is interpreted
astrue.
One way to have the compiler find this type of error is to put any
constants (or any r-value expressions) on the left side. Then if an=is
used, it will be an error:

if ( 6 = x)

Forgetting to put an ampersand (&)


on arguments
scanf()must have the address of the variable to store
input into. This means that often the ampersand address
operator is required to compute the addresses. Here's an
example:
int x;
char * st = malloc(31);
scanf("%d", &x);
/* & required to pass address to scanf() */
scanf("%30s", st);
/* NO & here, st itself points to variable! */

As the last line above shows, sometimes no ampersand is


correct.

Using the wrong format for


operand
C compilers donotcheck that the correct
format is used for arguments of
ascanf()call. The most common errors
are using the%fformat for doubles (which
must use the%lfformat) and mixing
up%cand%sfor characters and strings.

Size of arrays
Arrays in C always start at index 0. This
means that an array of 10 integers defined
as:
int a[10];
has valid indices from 0 to 9not10! It is
very common for beginners go one too far
in an array. This can lead to unpredictable
behavior of the program.

Integer division
Unlike Pascal, C uses the / operator for both real and integer division. It
is important to understand how C determines which it will do. If both
operands are of an integral type, integer division is used, else real
division is used. For example:
double half = 1/2;
This code setshalfto 0 not 0.5, because 1 and 2 are integer constants.
To fix this, we could change at least one of them to a real constant.
double half = 1.0/2;
If both operands are integer variables and real division is desired,
casting one of the variables todouble(orfloat) would do the trick.
int x = 5, y = 2;
double d = ((double) x)/y;

Loop errors
In C, a loop repeats the very next statement after the
loop statement. The code:
int x = 5;
while( x > 0 );
x--;
is an infinite loop. The semicolon after
thewhiledefines the statement to repeat as the null
statement (which does nothing). Removing the
semicolon will make the loop works as expected.
Another common loop error is to iterate one too many
times or one too few.

Not using prototypes


Prototypes tell the compiler important features of a function: the return
type and the parameters of the function. If no prototype is given, the
compilerassumesthat the function returns an int and can take any
number of parameters of any type.
One important reason to use prototypes is to let the compiler check for
errors in the argument lists of function calls. However, a
prototypemustbe used if the function does not return an int. For example,
thesqrt()function returns a double, not an int. The following code:
double x = sqrt(2);
will not work correctly if a prototype: double sqrt(double); does not
appear above it. Without a prototype, the C compiler assumes
thatsqrt()returns an int. Since the returned value is stored in a double
variable, the compiler inserts code to convert the value to a double. This
conversion is not needed and will result in the wrong value.
The solution to this problem is to include the correct C header file that
contains thesqrt()prototype(math.h).

Not initializing pointers


Anytime we use a pointer, we should be able to answer the
question:What variable does this point to?If we can not answer
this question, it is likely it doesn't point toanyvariable. This type
of error will often result in aSegmentation fault/Core Dumperror
on UNIX/Linux or a general protection fault under Windows.
Here's an example of this type of error.
#include <string.h>
int main() {
char * st; /* defines a pointer to a char or
array */
strcpy(st, "abc");
return 0;
}

char

There are two solutions to this problem. We could use an array or dynamically
allocate an array.
#include <string.h>
int main() {
char st[20]; /* defines an char array */
strcpy(st, "abc"); /* st points to char array */
return 0;
}
or
#include <string.h>
#include <stdlib.h>
int main() {
char *st = malloc(20); /* st points to allocated array*/
strcpy(st, "abc"); /* st points to char array */
free(st); /* don't forget to deallocate when done! */
return 0;
}
Actually, the first solution is much preferred for what this code does. Why?
Dynamical allocation should only be used when it is required. It is slower and
more error prone than just defining a normal array.

String Errors
Confusing character and string constants
C considers character and string constants as very different things.
Character constants are enclosed insingle quotes but string
constants are enclosed indouble quotes. String constants act as a
pointer to the actually string. Consider the following code:
char ch = 'A'; /* correct */
char ch = "A"; /* error */
The second line assigns the character variablechto the address of a
string constant. This should generate a compiler error. The same
should happen if a string pointer is assigned to a character constant:
const char * st = "A"; /* correct */
const char * st = 'A'; /* error */

Comparing strings with==


Never use the==operator to compare the value of strings. Strings
arechararrays. The name of achararray acts like a pointer to the string
(just like other types of arrays in C). Consider the following code:
char
char
if (
else

st1[] = "abc";
st2[] = "abc";
st1 == st2 ) printf("Yes");
printf("No");

This code prints outNo, Because the==operator is comparing thepointer


valuesofst1andst2, not the data pointed to by them. The correct way to
compare string values is to use thestrcmp()library function. If
theifstatement above is replaced with the following:
if ( strcmp(st1,st2) == 0 ) printf("Yes");
else printf("No");
the code will print outYes. For similar reasons, other relational operators
(<,>,etc.) cant be used with strings either.

Not null terminating strings


C assumes that a string is a character array with a
terminating null character. This null character has
ASCII value 0 and can be represented as
just0or'\0'. This value is used to mark the end of
meaningful data in the string. If this value is
missing, many C string functions will keep
processing data past the end of the meaningful
data and often past the end of the character array
itself until it happens to find a zero byte in memory.
Most C library string functions that create strings
will always properly null terminate them. Some do
not (e.g. strncpy()).

Not leaving room for the null


terminator
A C string must have a null terminator at the end of the meaningful data in the
string. A common mistake is to not allocate room for this extra character. For
example, the string defined below
char str[30];only has room for only 29 (not 30) actually data characters,
since a nullmustappear after the last data character.
This can also be a problem with dynamic allocation. Below is the correct way to
allocate a string to the exact size needed to hold a copy of another.
char * copy_str = malloc(strlen(orig_str) + 1);
strcpy(copy_str, orig_str);
The common mistake is to forget to add one to the return value ofstrlen().
Thestrlen()function returns a count of the data characters which
doesnotinclude the null terminator.
This type of error can be very hard to detect. It might not cause any problems
or only problems in extreme cases. In the case of dynamic allocation, it might
corrupt theheap(the area of the program's memory used for dynamic
allocation) and cause thenextheap operation (malloc(),free(),etc.) to fail.

THANK YOU FOR


YOUR
ATTENTION !

You might also like