What are the common causes of pointer bugs?

Uninitialized pointers** :** One of the easiest ways to create a pointer bug is to try to reference the value of a pointer even though the pointer is uninitialized and does not yet point to a valid address. For example: int *p; *p = 12; The pointer p is uninitialized and points to a random location in memory when you declare it. It could be pointing into the system stack, or the global variables, or into the program’s code space, or into the operating system. [Read More]

C code to dynamically allocate one, two and three dimensional arrays (using malloc())

One Dimensional Array int \*myarray = malloc(no\_of\_elements \* sizeof(int)); //Access elements as myarrayii 2 Dimensional Array Method1 int \*\*myarray = (int \*\*)malloc(nrows \* sizeof(int \*)); for(i = 0; i < nrows; i++) { myarrayii = malloc(ncolumns \* sizeof(int)); //allocating 1 D array = number of elements in column } // Access elements as myarrayiijj Method 2 (Contagious Allocation) int \*\*myarray = (int \*\*)malloc(nrows \* sizeof(int \*)); myarray00 = malloc(nrows \* ncolumns \* sizeof(int)); for(i = 1; i < no\_of\_rows; i++) myarrayii = myarray00 + (i \* ncolumns); // Access elements as myarrayiijj In either case, the elements of the dynamic array can be accessed with normal-looking array subscripts: array[i][j]. [Read More]

What is a dangling pointer? What are reference counters with respect to pointers?

A pointer which points to an object that no longer exists. Its a pointer referring to an area of memory that has been deallocated. Dereferencing such a pointer usually produces garbage. Using reference counters which keep track of how many pointers are pointing to this memory location can prevent such issues. The reference counts are incremented when a new pointer starts to point to the memory location and decremented when they no longer need to point to that memory. [Read More]