Memory Allocation Functions in C

This C Tutorial explains Different Memory Functions in C and Explain Their Use with Examples.

String handling functions, as we have seen, deal only with string-data. Then what about the processing of Non-String data, for example, an array of floats, an array of structures, an array of pointers etc.. Further, it’s not uncommon for non-string data to contain’0′ (NULL) characters. ANSI C library provides a related set of functions called memory functions for handling such needs.

Let’s consider the prototypes of some of the most common memory functions below,

    void *memcpy(void *dst, const void *src, size_t lenbytes);
    void *memmove(void *dst, const void *src, size_t lenbytes);
    void *memcmp(void const *dst, const void *src, size_t lenbytes);
    void *memchr(void const *a, int ch, size_t lenbytes);
    void *memset(void *a, int ch, size_t lenbytes);

Notice the type of arguments ‘void *’ in function prototypes which means pointers-to-any_type can be passed to pointers of type ‘void *’. In addition, unlike strn— functions, memory functions don’t stop when they encounter the first NULL character. These functions deal with arbitrary sequences of bytes. Let’s take examples to understand them well,

    char msg[] = "tomorrow's sunday, we gonna out for picnic!";
    char dst[100];
    size_t nbytes;
 
    memcpy(dst, msg, sizof(msg));  /* copies the entire 'msg' to 'dst' */
    memcpy(dst, msg, 20);          /* copies 20 bytes from 'msg' to 'dst' */

What happens if we try to copy an array of ‘ints’, for example,

advertisement
advertisement
    int num[15] = {1,0,5,6,7,12,87,34,98,111,90,345,09,689,1};
    int dst[15];
 
    memcpy(dst, num, sizeof(num));    /* entire 'num' copied into 'dst' */

What if part of ‘num’ to be copied, for ex. 6 elements, then multiply the count by size of one element as:

    memcpy(dst, num, 6 * sizeof(num[0]));

There’s a drawback associated with memcpy() which is while copying if source array and destination array overlaps in some way, result is undefined. memmove() is best choice if there’s any possibility of overlapping of source and destination array. Consider a program,

Note: Join free Sanfoundry classes at Telegram or Youtube
/*
 * memcpy_memmove.c -- program copies specified bytes from source array to
 * 'dst' array
 */
#include <stdio.h>
#include <string.h>
 
void show_val(const int [], int);
 
int main(void) 
{
    int val[SIZE] = {1,2,3,4,5,6,7,8,9,10};
    int target[SIZE];
    double dval[SIZE / 2]= {1.0,2.0,3.0,4.0,5.0};
    int i;
 
    printf("Original Array \'val\' of integers is: ");
    show_val(val, SIZE);
    puts("\n");
 
    puts("memcpy(): copying array of ints \'val\' to array of ints "
         "\'target\'");
    memcpy(target, val, SIZE * sizeof(val[0]));
    printf("target becomes: ");
    show_val(target, SIZE);
    puts("\n");
 
    puts("memmove(): copying range 0-5 of \'val\' to 2-7 of \'target\'");
    memmove(target + 2, val, 5 * sizeof(val[0]));
    printf("target becomes: ");
    show_val(target, SIZE);
    puts("\n");
 
    puts("memcpy(): copying array of 5 doubles to array of 10 ints");
    memcpy(val, dval, (SIZE / 2) * sizeof(dval[0]));
    puts("Array of ints \'val\' becomes: ");
    show_val(val, SIZE);
    puts("\n");
 
    return 0;
}

Output is as follows:

Original Array 'val' of integers is:  1  2  3  4  5  6  7  8  9 10 
 
memcpy(): copying array of ints 'val' to array of ints 'target'
target becomes:  1  2  3  4  5  6  7  8  9 10 
 
memmove(): copying range 0-5 of 'val' to 2-7 of 'target'
target becomes:  1  2  1  2  3  4  5  8  9 10 
 
memcpy(): copying array of 5 doubles to array of 10 ints
Array of ints 'val' becomes: 
 0 1072693248  0 1073741824  0 1074266112  0 1074790400  0 1075052544

Notice that we, in the last case in above program, copied doubles to ints. Actually, memcpy() and memmove() functions don’t know the type of arguments, just copies byte by byte. we can, this way, copy values of any type to any type, for ex. we can copy array of structures to array of characters.

memcmp(): memcmp() function works exactly like strcmp() except that it takes arguments of type ‘void *’. Therefore, we can use memcmp() to compare array of ints, array of structures etc. For ex.

advertisement
/*
 * memcmp.c -- program compares specified bytes as unsigned bytes from
 * source array to 'dst' array
 */
#include <stdio.h>
#include <string.h>        /* for memory fun. prototypes */
#define SIZE 10
void show_val(int [], int);
 
int main(void)
{
    char dear[] = "u want to learn C programming.";
    char sure[] = "u want to learn, sure!";
    int val[SIZE] = {1,2,3,4,5,6,7,8,9,10};
    int target[SIZE] = {1,2,3,4,5};
 
    puts("character strings \'dear\' and \'sure\' are as:");
    puts(dear);
    puts(sure);
    puts("");
 
    puts("Let's compare \'dear\' and \'sure\'");
    if (memcmp(sure, dear, 15) == 0)
        /* first 15 bytes */
        puts("First 15 bytes of \'sure\' and \'dear\' Matched.\n");
 
    puts("Arrays of ints \'val\' and \'target\' are as:");
    printf("val: ");
    show_val(val, SIZE);
    printf("target: ");
    show_val(target, SIZE);
    puts("");
 
    puts("Let's compare \'val\' and \'target');
    if (memcmp(target, val, 5 * sizeof(int)) == 0)
        /* first 5 ints */
        puts("First 5 integers in \'val\' and \'target\' Matched.\n");
 
    return 0;
}
 
void show_val(int copy[], int n)
{
    int i;
 
    for (i = 0; i < n; i++)
       printf("%2d ", copy[i]);
 
    puts("");
}

Output of the program as:

character arrays 'dear' and 'sure' are as:
u want to learn C programming.
u want to learn, sure!
 
Let's compare 'dear' and 'sure'
First 15 bytes of 'sure' and 'dear' Matched.
 
Arrays of ints 'val' and 'target' are as:
val:  1  2  3  4  5  6  7  8  9 10 
target:  1  2  3  4  5  0  0  0  0  0 
 
Let's compare 'val' and 'target'
First 5 integers in 'val' and 'target' Matched.

memcmp() compares specified bytes in byte-by-byte manner as unsigned character bytes and returns 0 if two arrays are same or negative value if first argument is lower than second and positive value when first argument is higher than second.

memchr(): function searches specified bytes beginning at location specified by first argument for the first occurrence of character ‘ch’ and returns pointer to that location. If character doesn’t found, NULL is returned.

advertisement

memset(): function sets specified bytes beginning at location specified by first argument a with the character ‘ch’ given as 2nd argument returns pointer to first argument. For ex.

    int val[SIZE] = {1,2,3,4,5,6,7,8,9,10};
    memset(val, 0, 5 * sizeof(int));
 
    val becomes: 0 0 0 0 0 6 7 8 9 10

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

If you wish to look at all C Tutorials, go to C Tutorials.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.