Knowledgebase

Understanding Pointers and Memory in C Print

  • programminglanguages, programming, guide, howto, solution, zillionkinghost, hosting, support
  • 0

The central concept.

WHAT A POINTER IS

A variable holding a memory address.

WHY THEY EXIST

To access memory directly, pass large structures cheaply, and build dynamic data structures.

WHAT THE STACK IS

Memory for local variables, allocated and released automatically as functions are entered and left.

WHAT THE HEAP IS

Memory allocated explicitly, released explicitly.

WHAT GOES WRONG

Allocating and never freeing, leaking memory Freeing and then using, producing undefined behaviour Freeing twice Writing beyond an allocation, corrupting adjacent memory Returning a pointer to a local variable, which no longer exists

WHY UNDEFINED BEHAVIOUR IS DANGEROUS

The program may appear to work, and fail unpredictably later.

WHAT DISCIPLINE HELPS

Every allocation paired with its release Setting pointers to null after freeing Checking every allocation succeeded Bounds checked explicitly, always

WHAT TOOLS FIND

Leaks, invalid access and undefined behaviour, at runtime.

WHAT TO ALWAYS RUN

Those tools, during development.

WHAT TO NEVER ASSUME

That code without warnings is correct.


Was this answer helpful?
Back

Are you happy with your experience? Leave us a review on Trustpilot.


Trustpilot