C pointers - sharmasadhna/mylearnings GitHub Wiki

Pointer : variable which holds address of another variable

Need of pointer: To do dynamic memory allocation

IMP Points to remember: *When a pointer is declared it does not point anywhere. You must set it to point somewhere before you use it. int *p; *p = 4; //program crash *Pointer itself is stored in stack, the address which it points to is in heap.

*If a pointer in C is assigned to NULL, it means it is pointing to nothing. *Two pointers can be subtracted to know how many elements are available between these two pointers. *But, Pointer addition, multiplication, division are not allowed. *The size of any pointer is 2 byte (for 16 bit compiler).

Array & Pointers int a[10], x; int *pa;

  1. A pointer is a variable. We can do

pa = a and pa++. 2. An Array is not a variable.

a = pa and a++ ARE ILLEGAL.

Common Mistakes:

  1. Refer IMP POINT 1
  2. Illegal indirection : eg *p = (char ) malloc(100); / Malloc returns a pointer. so correct should be p = (char *) malloc(100) */ p = `y'; / If malloc fails p=NULL, so correct should be error handling if (p !=NULL){*p= 'y';} */

Dynamic Allocation 4 library functions defined under <stdlib.h> for dynamic memory allocation.

  • malloc() : Allocates requested size of bytes and returns a pointer first byte of allocated space; If the space is insufficient, allocation fails and returns NULL pointer.
  • calloc() : Allocates space for an array elements, initializes to zero and then returns a pointer to memory; calloc stands for "contiguous allocation"
  • free() : deallocate the previously allocated space
  • realloc(ptr, newsize) : Change the size of previously allocated space

Pointer To constant

  • const int *ptr;
  • int const *ptr;
  • *ptr=5 /*error: assignment of read-only location ‘*ptr’ */

Constant pointer:

  • int *const ptr = &i;
  • ptr =&j; /*error: assignment of read-only variable ptr */

constant pointer to constant

  • const int *const ptr = &i;
  • printf("ptr: %d\n", *ptr);
  • ptr = &j; /* error: assignment of read-only variable ‘ptr’*/
  • ptr = 100; / error: assignment of read-only location ‘ptr’/

Dangling Pointer case1: after free, dereference pointer --> seg fault case2: return local variable(not static) address from function --> undefined behaviour

Memory Leak case: did malloc but never freed the heap memory

⚠️ **GitHub.com Fallback** ⚠️