The best programs are written so that computing machines can perform them quickly and so that human beings can understand them clearly. A programmer is ideally an essayist who works with traditional aesthetic and literary forms as
well as mathematical concepts, to communicate the way that an algorithm works and to convince a reader that the results will be correct. Donald E. Knuth

Buffer Manipulation Functions in C

C offers some buffer manipulation functions which directly operates on blocks of memory. For e.g, memcpy is a function designed to copy a chunk of memory of specified length ( number of bytes ) from one location ( memory address ) to another. The functionality of memcpy is similar to strcpy but the latter stops copying the contents once a NULL character is encountered. However, memcpy doesn't consider the NULL character and simply copies the chunk of memory. Thus, buffer manipulation functions are much efficient when it comes to performance. Following table shows some of the commonly used buffer manipulation functions.

FunctionDescription
memcpyCopy specified number of bytes from one memory location to another.
memsetInitialize specified number of bytes in memory to NULL or any other value.
memcmpCompare the contents of two buffers ( memory blocks ).

Following program illustrates the use of memset function :

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

int main() {
    int *arr, i;
    arr = malloc(5 * sizeof(int)); /* allocate an array of 5 integers */
    printf("Array after allocation :-\n");
    for (i = 0; i < 5; i++) { /* all indices of 'arr' contain garbage values */
        printf("%d ", arr[i]);
    }
    memset(arr, 0, 5 * sizeof(int)); /* initialize all array elements to 0 */
    printf("\nArray after initialization :- \n");
    for (i = 0; i < 5; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}

Following program illustrates the use of memcpy and memcmp function :

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

int main() {
    char str1[] = "csegeek";
    char *str2;
    int len = strlen(str1);
    str2 = malloc(len * sizeof(char));
    memcpy(str2, str1, len); /* copy str1 into str2 */
    printf("str1 : %s\n", str1);
    printf("str1 is copied to str2\n");
    printf("str2 : %s\n", str2);
    if (!memcmp(str1, str2, len)) { /* compare str1 and str2 */
       printf("str1 and str2 are equal\n");
    }
    else {
       printf("str1 and str2 are not equal\n");
    }
    return 0;
}

For case insensitive comparison of strings, we can use memicmp function. There are other buffer manipulation functions which we haven't discussed here but you can always refer to them in header file documentation.

Back