I have a problem with validating the values of a size_t. How do I prevent negative values assigned to a size_t variable..
Here's the code that's causing the problems:
Code:
#include <stdio.h>
#include <stdlib.h>
#define DEFAULT_ARRAY_SIZE 2
void check_allocation(void * ptr, const char * func) {
if (!ptr) {
fprintf(stderr, "Allocation failed for %s\n", func);
//exit(EXIT_FAILURE);
}
}
unsigned int* create_array(size_t length) {//This fails if length is < 0
size_t _length = length <= 0 ? DEFAULT_ARRAY_SIZE : length;
fprintf(stdout, "create_array _length: %ld\n", _length);
unsigned int* ans = calloc(_length, sizeof(*ans));
check_allocation(ans, "create_array");
return ans;
}
unsigned int* create_array_2(signed int length) {//This does not fail if length is < 0
size_t _length = length <= 0 ? DEFAULT_ARRAY_SIZE : length;
fprintf(stdout, "create_array_2 _length: %ld\n", _length);
unsigned int* ans = calloc(_length, sizeof(*ans));
check_allocation(ans, "create_array_2");
return ans;
}
int main(int argc, char ** argv) {
unsigned int * arr = create_array(-12);
unsigned int * arr_2 = create_array_2(-12);
fprintf(stdout, "%p %p\n", (void*)arr, (void*)arr_2);//just to block warnings about unused vars
return 0;
}
The problem is in create_array function. If I pass a negative value to this function it fails in unpredictable ways(well unpredictable me).
If I use the function create_array_2 then I can check for a negative values and take corrective actions.
Is create_array_2 the correct way to valid the values used for something that will eventually be a size_t value?