Zack
Zack

Reputation: 385

Error handling in a C, void returning function

Giving this example function:

And giving that I can only change the else statement in the function, how should I handle a memory allocation error? I can't return some error code since the function returns void, I can't throw exceptions in C, I can't just stop the execution in a function for an error that could be minor relatively to the other things that the program is doing... should I just let the pointer be NULL and let the coder that is using my function to handle the errors after calling my function?

The only functions I can use are the function in these libraries: stdio.h, stdlib.h, string.h, stdarg.h

Thank you!

Upvotes: 3

Views: 2027

Answers (4)

jfa
jfa

Reputation: 1101

In class we do

printf("Error allocating memory.");
exit(1);

or simply exit(1). If your memory is full, there's not a lot you can do from there.

Upvotes: 2

alk
alk

Reputation: 70951

should I just let the pointer be NULL and let the coder that is using my function to handle the errors after calling my function?

Probably yes.

But not only "after" but also before, that is the coder needs to store a copy of the address the pointer being passed into your function points to. Because if the coder didn't and your function failed the program leaked memory, namly such which the pointed to address referenced.

char * p = malloc(42);

{
  char * p_save = p;

  f(&p_save, "");
  if (NULL == p_save)
  {
    /* log error or what ever is needed, including freeing p and return, exit or abort */
  }
  else
  {
    p = p_save;
  }
}

free(p);

Or just wrap that sick function into something that is more easy to handle:

int fex(char ** pp, const char * t)
{
  char * p = *pp; /* Store a backup, just in case. */

  f(pp, t);

  if (NULL == *pp)
  {
     *pp = p; /* Opps, restore ... */
     return -1; /* ... and indicate error. errno should already have been set by realloc in f. */
  }

  return 0; /* Good. */
}

or (a bit dirty):

char * fex(char * p, const char * t)
{
  f(&p, t);

  if (NULL == p)
  {
     return (char *) -1; /* ... and indicate error. errno should already have been set by realloc in f. */
  }

  return p; /* Good. */
}

Call the latter like:

char * p = malloc(42);

{
  char * tmp = fex(p, "");
  if ((char *) -1) == tmp)
  {
    perror("fex() failed");
  }
  else
  {
    p = tmp;
  }
}

free(p);

Upvotes: 2

user823738
user823738

Reputation: 17521

Usually this is handled like:

abort();

in many implementation of programs and libraries.

Upvotes: 1

user457015
user457015

Reputation: 981

*p = NULL;
syslog(LOG_ERR, "Memory allocation error");

Upvotes: 2

Related Questions