Playing with Memory

Gone are the old days when your C program ruled the entire computer’s domain. Back then, you could access any chunk of memory in the computer, manipulate it in all sorts of interesting ways, and not be concerned that your code’s actions would be restricted. Ah, those were good times.

Of course, such freedom meant your program could tear down the entire system. This danger didn’t seem to be a concern back in the day. Still, within its allocated memory chunk, your C code today can manipulate memory in all sorts of interesting ways. The key function is memcpy():

void * memcpy(void *restrict dst, const void *restrict src, size_t n);

Defined in the string.h header file, the memcpy() or “mem-copy” function copies n bytes of storage from memory location src to memory location dst. Both locations must be allocated in your code; you can’t specify direct storage addresses.

One common place I’ve seen memcpy() used is to duplicate a structure:

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

int main()
{
    struct person {
        int age;
        char name[12];
    } man = { 34, "George" };
    struct person *guy;

    /* output the structure */
    printf("%s is %d years old\n",man.name,man.age);

    /* allocate the buffer */
    guy = (struct person *)malloc( sizeof(struct person) );
    if( guy==NULL )
    {
        fprintf(stderr,"Unable to allocate memory\n");
        exit(1);
    }

    /* copy memory */
    memcpy(guy,&man,sizeof(struct person));

    /* output the duplicate structure */
    printf("%s is %d years old\n",guy->name,guy->age);

    return(0);
}

The struct person variable man is defined and declared right away. Its member’s values are output.

The malloc() function allocates a chunk of memory, guy, then memcpy() duplicates the contents of the man variable into the newly-allocated guy chunk.

Finally, the guy buffer’s output is displayed, which is identical to the original:

George is 34 years old
George is 34 years old

Of course, all this action is a bit much. You could just duplicate the structure from one variable to another, as this variation on the code demonstrates:

#include <stdio.h>

int main()
{
    struct person {
        int age;
        char name[12];
    } man = { 34, "George" };
    struct person guy;

    /* output the structure */
    printf("%s is %d years old\n",man.name,man.age);

    /* copy structure */
    guy = man;

    /* output the duplicate structure */
    printf("%s is %d years old\n",guy.name,guy.age);

    return(0);
}

This version is shorter, and it does the same thing: guy = man takes care of everything.

The true advantage of memcpy() is that it can duplicate the contents of memory into a void buffer. Once there, you can examine it as raw data or however you please. I cover this process in next week’s Lesson.

Leave a Reply