Home > Blockchain >  How do you print utmp struct's data in utmp.h?
How do you print utmp struct's data in utmp.h?

Time:10-24

I want to learn to use the functions and data structures that come with utmp.h. In the code below I wanted to iterate through the utmp structs and print their data fiels.

#include <stdio.h>
#include <utmp.h>

int main()
{
        struct utmp *data;
        data = getutent();
        int i = 0 ;
        while(data != NULL)
        {
                  i;
                printf("%s\n" , data->ut_id);
                data = getutent();
        }
        printf("%d" , i);
        return 0 ;
}

Even though ut_id is of type char[4], when I run the code I get this warning:

warning: ‘__builtin_puts’ argument 1 declared attribute ‘nonstring’ [-Wstringop-overflow=]

How can I fix it?

CodePudding user response:

This warning is the result of the gcc-specific attribute __attribute_nonstring__, which is used as an indicator that an array of characters does not necessarily end in a NUL character, and therefore may not be safe to use with the standard library string functions. The utmp struct in Linux is defined with that attribute on its character array fields.

To work around that warning, you can use the printf() modifier %.*s which specifies the fixed width output of a character array, like this:

printf("%.*s\n" , (int)(sizeof data->ut_id), data->ut_id);

(you could just use 4 for the second argument, but sizeof is more flexible).

  • Related