C learners are generally pretty comfortable with the str… series of functions:
- strlen()
- strcpy()
- strcat()
- strcmp()
- strlwr()
- strupr()
However, I generally find a very poor awareness of the mem… series of functions:
- memcpy()
- memmove()
- memset()
- memchr()
These functions are extremely useful when dealing with data in memory. So first let us differentiate between “strings” and just “data”. A string in C is a sequence of characters terminated by the null character. Any arbitrary data in memory, therefore, cannot be considered to be a string. The strcpy()
function, thus, copies a source string to a destination memory location, and while doing so, performs the following:
- Stops copying the moment it encounters the terminating null character in the source string
- Ensures that the destination is also null terminated.
The mem… series of functions do not assume that they are dealing with strings and hence do not care about the presence or absence of the null character. A brief explanation of the mem… functions is given below:
void* memcpy(void *destination, const void *source, size_t num);
This function copiesnum
number of bytes fromsource
todestination
and returns a pointer to the destination block.void* memmove(void *destination, const void *source, size_t num);
This function also copiesnum
number of bytes fromsource
todestination
and returns a pointer to the destination block, but can handle cases where the source and destination regions overlap. This is a safer form of copying data. Do not go by it’s deceptive name: this function copies data!void* memset(void *ptr, int value, size_t num);
This function is used to fill a block of memory with a particularvalue.
The block is pointed to byptr
and the size of the block is passed vianum.
The most practical use of this function perhaps is initializing a block of memory to zeros.void* memchr(const void *ptr, int value, size_t n);
This function searches for the first occurrence of the givenvalue
within the block of memory of sizen
bytes, starting at the location pointed to byptr
. If the value was found, it returns a pointer to that byte within the memory block, and if the value was not found, it returnsNULL
.
Given below is a sample implementation of the calloc()
function, using the malloc()
and memset()
functions:
void* calloc(size_t num, size_t size) { void *ptr; if ((ptr = malloc(num*size)) memset(ptr,0,num*size); return ptr; }
Related Articles
1 user responded in this post