clockley1
clockley1

Reputation: 494

Is this code nonportable or unsafe

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

Upvotes: 4

Views: 114

Answers (1)

Carl Norum
Carl Norum

Reputation: 224864

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.

Upvotes: 2

Related Questions