memset

The memset function is used to set a block of memory to a specific value. A common use of memset is to set a whole block of memory to a NULL state, where all bytes are NULL.

The memset function requires three arguments. The first argument is an address to the memory block that we want to set. The second argument is the value that will be used to initialize the block of memory. Finally, the third argument is the size of the memory block.

The function free has undefined behavior if the address passed as a parameter does not pointer to a valid, heap allocated, block returned by the malloc function. Always make sure you are passing a valid memory address to free.

Accessing memory that has been passed to free

A common problem happens when memory that has been freed is accessed again. If this happens, the result is undefined, since any memory that has been freed can be reused by the program to other purposes. To avoid such invalid accesses, it is common to assign NULL to a pointer that has been recently sent to the free function.

Example

The following code shows an example of the memset function:

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

int main()
{
        int i;
        int num_elements = 10;
        int *p;
        p = (int *)malloc(sizeof(int)*10);
        memset(p, 0, 10);
        for (i=0; i<num_elements; i++) {
                printf("the value is %d\n", p[i]);
        }
        free(p);
        return 0;
}
Article created on 2008-08-19 22:03:31

Post a comment