Skip to content

anthony-aleman/Calloc-Implementation

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 

Repository files navigation

Calloc-Implementation

Here is my implementation of the dynamic memory allocation function calloc()

void * myCalloc(size_t numItems, size_t size) {
    void *pointer = malloc(numItems * size);

    // check if malloc failed
    if (pointer == NULL) {
        return NULL;
    }

    unsigned int i = 0;

    // initialize memory to 0
    while (i < (numItems * size))
    {
        *((char *)pointer + i) = 0;
        i++;
    }
    

    return pointer;
}

Assigning Integer items with my implementation is as follows:

int *p;

int numElements = 5;

int size = sizeof(int);

p = (int*)myCalloc(numElements, size);

if (p == NULL){
    printf("Memory allocation failed\n");
} else {
    // Assigning Values to allocated memory
    for (int i = 0; i < numElements; i++)
    {
        p[i] = i;
    }
    // Printing values in allocated memory
    for (int i = 0; i < numElements; i++)
    {
        printf("%d\n", p[i]);
    }

        
}
free(p);

About

Learning C by implementing calloc()

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages