简体   繁体   中英

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!

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

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.

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);

Usually this is handled like:

abort();

in many implementation of programs and libraries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM