Book Image

Learn C Programming

By : Jeff Szuhay
Book Image

Learn C Programming

By: Jeff Szuhay

Overview of this book

C is a powerful general-purpose programming language that is excellent for beginners to learn. This book will introduce you to computer programming and software development using C. If you're an experienced developer, this book will help you to become familiar with the C programming language. This C programming book takes you through basic programming concepts and shows you how to implement them in C. Throughout the book, you'll create and run programs that make use of one or more C concepts, such as program structure with functions, data types, and conditional statements. You'll also see how to use looping and iteration, arrays, pointers, and strings. As you make progress, you'll cover code documentation, testing and validation methods, basic input/output, and how to write complete programs in C. By the end of the book, you'll have developed basic programming skills in C, that you can apply to other programming languages and will develop a solid foundation for you to advance as a programmer.
Table of Contents (33 chapters)
1
Section 1: C Fundamentals
10
Section 2: Complex Data Types
19
Section 3: Memory Manipulation
22
Section 4: Input and Output
28
Section 5: Building Blocks for Larger Programs

Memory leaks

One of the main challenges of heap management is to prevent memory leaks. A memory leak is when a block of memory is allocated and the pointer to it is lost so that it cannot be released until the program quits. The following is a simple example of a memory leak:

Card* pCard = (Card*)calloc( 1 , sizeof( Card );
...
pCard = (Card*)calloc( 1 , sizeof( Card ); // <-- Leak!

In this example, pCard first points to one block of heap memory and then is later assigned to another. The first block of memory is allocated but, without a pointer to it, it cannot be freed. To correct this error, call free() before reassigning pCard.

A more subtle leak is as follows:

struct Thing1 {
int size;
struct Thing2* pThing2
}

struct Thing1* pThing1 = (struct Thing1*)calloc( 1 , sizeof(Thing1) );
Thing1->pThing2 = (struct Thing2*)calloc( 1 , sizeof(Thing2) );
...
free( pThing1 ); // <-- Leak!

In this example, we create theThing1 structure, which...