This article continues the one published two weeks ago: Top 101 mistakes done by novice programmers C, Top 101 mistakes done by novice programmers C – part 2  and Top 101 mistakes done by novice programmers C – part 3

 

 

13. Pointers mistakes

13.a Not assigning a pointer to memory address before using it

The following is the most common mistake:

 

int *x;

    *x = 100;

x must be allocated (consider using a malloc)

 

13.b Not releasing memory

Normally I test my algorithms using a simple program, for example:

int main(int arc, char **argv)
{
    char *myPointer;
    myPointer = (char *)malloc(100);
    
    // some code working on the pointer….
    // ….
    
    exit(0);
}

so when I've tested my code I can copy and paste into my real project…… In this case when the execution of the program reaches the exit statement, the OS release the allocated memory, when I copy the code in a function nobody will take care of this problem, so I MUST add a free statement as follows 


int function(void)
{
    char *myPointer;
    myPointer = (char *)malloc(100);
    
    // some code working on the pointer….
    // ….

    free(myPointer);
    return;

}


13.c Assigning Value to Pointer Variable

int * ptr , m = 100 ;
      ptr = (int *) malloc(1);
      ptr = m ;            // Error on This Line



the correct way is:

 

int * ptr , m = 100 ;
      ptr = (int *) malloc(1);
 

      *ptr = m ;           // or ptr = &m; depending on what do you want to do



13.d Not Dereferencing Pointer Variable

      int * ptr , m = 100 ;

 

      ptr =  &m ;

      printf("%d",ptr);     // Error on this Line

In the above code you are print the address of m, not its content. To print the content 9you have to do:

 

      int * ptr , m = 100 ;

      ptr =  &m ;

      printf("%d",*ptr);


13.e Many C library functions malloc's memory which MUST be freed: i.e.: strdup(),

 

char *oldString = "Old String";

char *newStrig = strdup(oldString);

...

...

...

...

free(newString);

Remeber the free statement.

 

 

13.f Free only allocated pointers.

Take a look to the following code:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char *p;
    int i=0;
    printf("%d\n", i);
    free(p);
    exit(0);
}

the p pointer has not been allocated, so when you'll execute the program it will crash and produce a core dumped message.

 



Part five in the next fifteen days.

Gg1