Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this code nonportable or unsafe

Tags:

c

malloc

I'm writing some code that depends on calloc and was wondering it would be safe to repoint the pointer to stack space if calloc failed, then set the pointer to NULL before the call to free() or skip it altogether. Works great of my 386 linux box.

char *str = NULL;
int usestackspace = 0;
char str1[16] = {0};

str = (char *)calloc(1, sizeof(pid_t));

if (str == NULL) {
    sleep(1);
    str = (char *)calloc(1, sizeof(pid_t));
}

if (str == NULL) {
    fprintf(stderr, "watchdog: %s\n", strerror(errno));
    usestackspace = 1;
    str = str1;
}

if (str == NULL) {
    return -1;
}
like image 943
clockley1 Avatar asked Dec 10 '25 02:12

clockley1


1 Answers

As long as str1 doesn't go out of scope your code is pretty much fine. You do have one real error (that should be generating a warning, though it probably doesn't matter at runtime):

  • str = &str1 isn't a valid assignment without an explicit cast. You probably want str = str1.

One potential problem:

  • If you were depending on the implicit setting-to-zero of memory by calloc, you need to initialize str1. Use char str1[16] = { 0 } or call memset, for example.

And a couple of minor notes:

  1. You don't have to cast the return value of calloc in a C program.

  2. You have free(str) and str = NULL in the if statement, but both are no-ops - the if statement condition ensures that str already is NULL.

like image 164
Carl Norum Avatar answered Dec 11 '25 18:12

Carl Norum