'Ignoring return value' warning

1.9k Views Asked by At

I am receiving warning: ignoring return value of 'getcwd', declared with attribute warn_unused_result #define get_current_dirr when running this code:

#define get_current_dir getcwd
FILE *open_particle_data()
{
    FILE *data_file;
    char data_file_name[] = "particle_data.txt";
    char buff[FILENAME_MAX];
    get_current_dir(buff, FILENAME_MAX);
    char *output_dir;
    char str1[] = "/output_data/";
    output_dir = malloc(strlen(buff) + strlen(str1) + strlen(data_file_name) + 1);
    strcpy(output_dir, buff);
    strcat(output_dir, str1);
    strcat(output_dir, data_file_name);
    data_file = fopen(output_dir,"w");
    free(output_dir);
    return data_file;

Any help would be appreciated. Thanks

2

There are 2 best solutions below

0
John Bollinger On

Various functions in Glibc are annotated in a way that suggests to the compiler that it is suspicious for their return values to be ignored. When GCC observes during compilation that the return value of such a function indeed is ignored, it (by default) issues a warning about that. That is what you are seeing.

The C language allows you to ignore function return values, but doing so is often a mistake. In particular, many functions' return values contain information about function success or failure, and neglecting to account for the possibility of failure can lead to erroneous, possibly even destructive behavior. And that may not manifest until later, making such issues difficult to debug.

getcwd() in particular returns a null pointer when it fails, and in that case you cannot rely on it to have written a valid string into the specified buffer. A robust program would detect such a return value and handle it gracefully. For example, the program might emit a diagnostic message and terminate when it observes getcwd() to fail.

On the other hand, if you just want to silence the error without actually fixing the issue, then you can cast the return value to void to explicitly indicate to GCC and to some other compilers that you are intentionally ignoring it. I do not recommend this.

0
Luis Colorado On

As an extension to the response of John Bollinger, I'll say that getcwd() returns a pointer to the passed buffer in case of successful execution, and NULL in case of error. You should use that returned value, in order to see if getcwd() executed correctly, as some cases could make it fail:

  • the size of the passed buffer is zero.
  • a component of the pathname no longer exists (this can happen if the paren directory of some visited directory has been eliminated)
  • The buffer size does not fit the actual path name.
  • read or execute permission in some of the directories up to the root is not granted to the process.

Being the most common that you have provided a short buffer to store the path.