1. Home
  2. Computing & Technology
  3. C / C++ / C#

C Tutorial - About Pointers

By , About.com Guide

7 of 10

About malloc and free

I named the variable pb to remind myself that it is a pointer though I recommend using much longer variable names than this! Other schemes involve adding a prefix of ptr or a suffix of _ptr. Whatever naming convention you use, make sure it survives the "Six Month Test"- if you come back and read your code in 6 months time, can you still understand it?

Allocating Memory

I've used malloc(), free() and sizeof() without really describing how they should be used. Note that sizeof() is an operator, not a function. If it was a function it would be called at runtime. However as the compiler knows how big types and variables are (during compilation), it can substitute the actual size and use it during compilation.

The functions malloc() and free() are closely tied in that malloc() requests memory from the operating system and free() returns memory allocated by malloc() back. When you use malloc() you should do the following:

  1. Specify the amount of RAM you need in the call, perhaps using sizeof().
  2. Check that the pointer returned is not NULL. This occurs if malloc() cannot allocate any RAM.
  3. Track the memory allocated, by keeping the original pointer or a copy of it and passing the pointer to free() when you no longer need the memory.
On the next page : Some Rules for using Pointers
Explore C / C++ / C#
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#

©2009 About.com, a part of The New York Times Company.

All rights reserved.