Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error handling in a C, void returning function

Tags:

c

malloc

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!

like image 326
Zack Avatar asked Dec 12 '25 09:12

Zack


2 Answers

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);
like image 175
alk Avatar answered Dec 14 '25 07:12

alk


*p = NULL;
syslog(LOG_ERR, "Memory allocation error");
like image 24
user457015 Avatar answered Dec 14 '25 05:12

user457015



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!