user3043079
user3043079

Reputation: 13

Warning on using getline() in C

int bytes_read;
int nbytes = 100;
char *Name;

Name = (char *) malloc (nbytes + 1);
bytes_read = getline (&Name, &nbytes, stdin);

/* Warning Message when compiled
   warning: incompatible pointer types passing 'int *' to
   parameter of type 'size_t *' (aka 'unsigned long *')
   [-Wincompatible-pointer-types]
   ...bytes_read = getline (&Name, &nbytes, stdin);
                                   ^~~~~~~
*/

I am trying to use getline() function in C. It ran good when compiled but there is a warning. Why there is a warning? I cant figure it out.

Upvotes: 0

Views: 1428

Answers (4)

haccks
haccks

Reputation: 106012

Second argument &nbytes of getline you are passing to is of type int * but getline expects second argument of type size_t *.
Change the declaration

int nbytes = 100;  

to

size_t nbytes = 100;  

or you can cast the second argument as

bytes_read = getline (&Name, (size_t *)&nbytes, stdin);


(For int nbytes = 100;, never cast &nbytes to size_t *)

Upvotes: 0

Keith Thompson
Keith Thompson

Reputation: 263247

The second argument to the getline function (which is defined by POSIX but not by ISO C, BTW) is of type size_t*. Passing an argument of type int*, as you're doing, is a constraint violation, requiring a compile-time diagnostic. A compiler may (and IMHO should) reject the call as a fatal error; gcc chooses to issue a mere warning by default.

Your code, if it compiles, causes getline to attempt to treat an int object as if it were a size_t object. This may happen to "work" if int and size_t happen to be the same size on your system. If they're not, arbitrary bad things can happen -- including your program appearing to work "correctly" until it blows up at the most inconvenient possible moment.

Define nbytes as a size_t object, not as an int. (Don't even think about casting the pointer from int* to size_t*; that will silence the warning, and your code might still appear to "work", but it will not solve the problem.)

Upvotes: 2

Tomcatus
Tomcatus

Reputation: 167

The warning explains it rather clear - you are using incompatible types. int * and unsigned long * are quite different, but the compiler will do a cast and just warns you that you can lose some data, e.g. when passing signed data like -2

Upvotes: 0

newfurniturey
newfurniturey

Reputation: 38436

The second parameter for getline() is of type size_t, not int:

ssize_t getline(char **lineptr, size_t *n, FILE *stream)

size_t is an unsigned long that's used to represent "sizes" (which can't be less than 0). It's an implicit cast from int to size_t and your code should execute fine as long as you never pass in a negative value. However, I would recommend updating it to use size_t instead:

ssize_t bytes_read;
size_t nbytes = 100;

Upvotes: 0

Related Questions