Monday, June 20, 2011

C Programming Tips and Tricks – Part1:

Signed/Unsigned types:

• Use unsigned types for bit field manipulation and binary masks. For others, use signed types.
• Use casts in expression to avoid compiler interpretation to choose results.

Malloc(strlen(str)) => Wrong (because, need to add 1 byte for null termination character)
Malloc(strlen(str)+1) => Right

Switch:
In switch statement, each case should be labeled by integer-valued constants.

Static:
• For variables => it retains its value between calls; scope is limited to inside function.
• For functions => visible in only this file.

Extern:
• For variables => defined it elsewhere.
• For functions => Global scope(and is redundant)

Declarations and definitions:
Extern int i => it is the declaration (doesn’t reserve space in memory)
Int i =10 => it is the declaration and definition (Creates type and name of the object and reserve space)

Typedef:
Typedef int integer;
Unsigned integer I; // illegal

Process Address Space:

Unmapped region => For null pointer references.


Object file:
• It contains Data segment, Text segment and details of the size required for BSS segment.

Dangling pointer -> doesn’t reference anything. (Generally occurs, when returning address of a local auto variable from function, as the variable no longer exists after function exited)


Memory Issues:
Memory Corruption:
Freeing or overwriting memory that is still in use.

Memory Leak:
Not freeing memory that is not in use.


Declaration of Structures and Unions:
struct/union optional-tag
{
type1 var1;
type2 var2;
} optional_variable_definitions;

→ For Unions, all the members have an offset zero.



No comments:

Post a Comment