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 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 mallocMAXSTR ; can hold a string of up to MAXSTR characters.
pc mallocstrlenHello ; can hold a copy of "Hello" with the terminating nullcharacter
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 sizeofdouble ; can hold up to double precision numbers.double pi ;
pd malloc sizeofpi ; can hold up to double precision numbers.
BE CAREFUL: If p is a pointer, then sizeofp is the number of bytes to hold a pointer, not what p points to:
int ip ;
ip malloc sizeofip ; WRONG! allocate space for an integer pointer.
ip malloc sizeofip ; CORRECT! allocate space for an integer.
ip malloc sizeofint ; ALSO CORRECT: take the size of the type.
Space no longer needed must be returned to the memory allocator using free:
pc mallocMAXSTR ; get space for a string
use the allocated space
freepc ; free up the space associated with pc
Orphaned storage:
char bufMAXSTR ;
pc mallocMAXSTR ;
pc buf ;
Dangling references:
pc mallocMAXSTR ;
char pc pc ;
use the allocated space
freepc ;
work without changing pc or pc
pc X ; PROBLEM: space was freed may have been reallocated
pcZ ; PROBLEM: pc 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
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
