1

I'm trying to learn and better understand splint, and I'm wondering about an error that I get from this code:

#include <stddef.h>
#include <stdlib.h>
#include <string.h>

/*@null@*/ /*@only@*/ char *dupStr(const char *str) {
    char *copy;
    size_t len;

    len = strlen(str) + 1U;
    if (!(copy = malloc(len * sizeof *str))) {
        return NULL;
    }
    (void) strncpy(copy, str, len);
    return copy;
}

The error is:

Splint 3.1.2 --- 26 Feb 2013

test.c: (in function dupStr)
test.c:13:9: New fresh storage copy (type void) cast to void (not released):
                (void)strncpy(copy, str, len)
  A memory leak has been detected. Storage allocated locally is not released
  before the last reference to it is lost. (Use -mustfreefresh to inhibit
  warning)

Finished checking --- 1 code warning

Is the correct solution to assign the return value to copy instead of throwing it away (it gets rid of the warning)?

potrzebie
  • 1,768
  • 1
  • 12
  • 25

1 Answers1

0

You don't want to ignore the return value of strncpy, that's why splint complains. You want something like:

if (strncpy(copy, str, len) == NULL)
    return NULL;
lbolla
  • 5,387
  • 1
  • 22
  • 35