Question: NULL, pointer to nothing, is a form of 0 , meaning a NULL pointer is false and all other pointer values are true. Space is

NULL, pointer to nothing, is a form of 0, meaning a NULL pointer is false and all other pointer values are true.
Space is allocated by calling malloc with the number of bytes needed (for strings this is always one more than the maximum length of the string to be stored):
char *pc = malloc(MAXSTR +1) ; // can hold a string of up to MAXSTR characters.
pc = malloc(strlen("Hello!")+1) ; // can hold a copy of "Hello" with the terminating nullcharacter '\0'.
The size given to malloc is always in bytes; the sizeof operator allows us to get the size in bytes of any type:
double *pd ;
pd = malloc(100* sizeof(double)) ; // can hold up to 100 double precision numbers.double pi =3.14159 ;
pd = malloc(100* sizeof(pi)) ;// can hold up to 100 double precision numbers.
BE CAREFUL: If p is a pointer, then sizeof(p) is the number of bytes to hold a pointer, not what p points to!:
int *ip ;
ip = malloc( sizeof(ip)) ;// WRONG! allocate space for an integer pointer.
ip = malloc( sizeof(*ip)) ;// CORRECT! allocate space for an integer.
ip = malloc( sizeof(int)) ;// ALSO CORRECT: take the size of the type.
Space no longer needed must be returned to the memory allocator using free():
pc = malloc(MAXSTR+1) ;// get space for a string
//... use the allocated space ...
free(pc) ;// free up the space associated with pc
Orphaned storage:
char buf[MAXSTR+1] ;
pc = malloc(MAXSTR +1) ;
pc = buf ;
Dangling references:
pc = malloc(MAXSTR +1) ;
char *pc1= pc ;
//... use the allocated space ...
free(pc) ;
//... work without changing pc or pc1...
*pc ='X' ;// PROBLEM: space was freed - may have been reallocated
*pc1='Z' ;// PROBLEM: pc1 aliased pc, so its space was also freed

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!