0

I wrote a simple code (part of it below) and use splint to check for any warnings. But Splint is complaining. What might be the issue I am missing?

Splint Warning

malloctest.c:24:3: Return value (type char *) ignored: gets(p)
  Result returned by function call is not used. If this is intended, can cast
  result to (void) to eliminate message. (Use -retvalother to inhibit warning)

Code part

p= (char*)malloc(BUFFER*sizeof(char));

    if(p==NULL)
        {
            printf("the memory could not be allocated");
        }
    else
    {
        gets(p);  //line 24
        printf("the name entered is \n%s\n",p);
    }

Thanks in Advance!

Shash
  • 4,160
  • 8
  • 43
  • 67

3 Answers3

3

gets() returns a char* to indicate success or failure, which the code is ignoring hence the warning.

However, with gets() there is no way to prevent buffer overrun. Instead, you can use scanf() with "%Ns" format specifier (or fgets() if the string can contain spaces):

if (1 == scanf("%9s", p)) /* if BUFFER(_SIZE ?) was 10.
                             The 'N' in the format specifier
                             must be 1 less than size of
                             the buffer to allow for null
                             terminator. */
{
}
hmjd
  • 120,187
  • 20
  • 207
  • 252
1

You should avoid using gets(), always!

gets() is a very unsafe function because it doesn't check the length of the buffer and this could lead into a potential buffer overflow.

#include <stdio.h>
int main(void) {
  char buffer[10];
  gets(buffer);
  puts(buffer);
  return 0;
}

If you for example input 0123456789 10 11 12 13 then you have a big problem.

It is better to use fgets() instead:

#include <stdio.h>
int main(void) {
  char buffer[10];
  fgets(buffer, sizeof buffer, stdin);
  puts(buffer);
  return 0;
}
Pablo
  • 13,271
  • 4
  • 39
  • 59
  • Don't forget that C11 has [gets_s](http://en.cppreference.com/w/c/io/gets) as a replacement. –  Sep 28 '12 at 09:32
  • and when will C11 be ever supported? Afaik c99 is still not widely by all major C-compilers (unless I'm very much mistaken) I find `fgets` more elegenat anyway. – Pablo Sep 28 '12 at 18:19
0

gets(p) has a char* return value which you aren't storing. This isn't realy a problem but splint just reminds you of that.

Minion91
  • 1,911
  • 12
  • 19