I have seen a few different ways of doing malloc error checking. Is one way better than the other? Are some exit codes better than others? Is using fprintf with stderr better than using a printf statement? Is using a return instead of an exit better?
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(1);
}
res = malloc(strlen(str1) + strlen(str2) + 1);
if (!res) {
fprintf(stderr, "malloc() failed: insufficient memory!\n");
return EXIT_FAILURE;
}
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(-1);
}
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(EXIT_FAILURE);
}
char *ptr = (char *)malloc(sizeof(char) * some_int);
if (ptr == NULL) {
fprintf(stderr, "failed to allocate memory.\n");
return -1;
}
char* allocCharBuffer(size_t numberOfChars)
{
char *ptr = (char *)malloc(sizeof(char) * numberOfChars);
if (ptr == NULL) {
fprintf(stderr, "failed to allocate memory.\n");
exit(-1);
}
return ptr;
}
malloc
failures. A user of a word processor doesn't want the application to crash just because the operation that they are attempting runs into memory resource limits. At the very least, if there is some relevant notion of state, perhaps state can be saved somehow before exiting. Don't think that amalloc
failure has to automatically terminate your program.malloc
.