Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The GNU C Programming Tutorial - Pointers and initialization

Node:Pointers and initialization, Next:, Previous:Pointer types, Up:Pointers



Pointers and initialization

You should not initialize pointers with a value when you declare them, although the compiler will not prevent this. Doing so simply makes no sense. For example, think about what happens in the following statement:

int *my_int_ptr = 2;

First, the program allocates space for a pointer to an integer. Initially, the space will contain garbage (random data). It will not contain actual data until the pointer is "pointed at" such data. To cause the pointer to refer to a real variable, you need another statement, such as the following:

my_int_ptr = &my_int;

On the other hand, if you use just the single initial assignment, int *my_int_ptr = 2;, the program will try to fill the contents of the memory location pointed to by my_int_ptr with the value 2. Since my_int_ptr is filled with garbage, it can be any address. This means that the value 2 might be stored anywhere. anywhere, and if it overwrites something important, it may cause the program to crash.

The compiler will warn you against this. Heed the warning!

 
 
  Published under free license. Design by Interspire