Skip to main content
1 of 2
pacmaninbw
  • 24.9k
  • 11
  • 46
  • 109

##Error Checking When using malloc(), calloc() or realloc() in C make sure to check the return value before using the memory, if any of these functions fail they return NULL. Accessing memory through a NULL pointer causes unknown behavior, the best you can hope for is the program crashes, the worst in the point corrupts memory yielding incorrect results.

int* array_initialize(int size) {
    int *array = calloc(size, size * sizeof(int));
    if (array == NULL)
    {
        fprintf(stderr, "calloc failed in array_initialize\n");
        exit(EXIT_FAILURE);
    }
}

The function array_size() is not safe, if the array is completely full, the pointer will walk off the end of the array and into other memory. The code should pass the maximum size of the array into the function as well and limit the while loop.

A better implementation might be to use a struct that contains the size of the memory allocated as well as the memory allocated.

pacmaninbw
  • 24.9k
  • 11
  • 46
  • 109