Warning of deceived objects in an idle state after reuse failure

I am completing my function to safely retrieve a string, and decided to turn off my compiler warnings to see if any of my codes raised flags.

I am currently receiving the following compiler warnings on the Pelles C IDE:

stringhandle.c(39): warning #2800: Potentially dangling object 'str' used after call to function 'realloc'. stringhandle.c(50): warning #2800: Potentially dangling object 'str' used after call to function 'realloc'. 

Here is my function (read below if you would rather read the whole question before reading the code):

 char *getstr(void) { char *str, *tmp; int bff = STRBFF, ch = -1, pt = 0; if(!(str = malloc(bff))) { printf("\nError! Memory allocation failed!"); return 0x00; } while(ch) { ch = getc(stdin); if (ch == EOF || ch == '\n' || ch == '\r') ch = 0; if (bff <= pt) { bff += STRBFF; if(!(tmp = realloc(str, bff))) { free(str); //line 39 triggers first warning str = 0x00; printf("\nError! Memory allocation failed!"); return 0x00; } str = tmp; } str[pt++] = (char)ch; } str[pt] = 0x00; if(!(tmp = realloc(str, pt))) { free(str); //line 50 triggers second warning str = 0x00; printf("\nError! Memory allocation failed!"); return 0x00; } str = tmp; return str; } 

I think I understand why they warn me that str might hang out. I release the allocated space pointed to by str if an error occurs, however my function has no further calls to str after it is freed. As a fix, I just tried to make free(str) and then str = 0x00 . Shouldn't this make the str pointer no longer hang out? Is this related to my tmp pointer? I do not release or set tmp to 0x00 , since it should be 0x00 if realloc fails. But should I set it to 0x00 on success, as it still technically accurately indicates where str no longer needed?

In short:

  • Why does my compiler warn that str might hang?
  • How to remove a warning?
  • Am I handling the tmp pointer correctly?
+4
source share
1 answer

To illustrate my points:

 #include <stdio.h> #include <stdlib.h> static inline void * myrealloc(void *org, size_t newsize) { char * new; new = realloc(org, newsize); if (!new) { fprintf(stderr, "\nError! Memory allocation failed!\n"); free (org); return NULL; } return new; } char *getstr(void) { #define STRBFF 256 char *str = NULL; size_t size , used ; for (size=used=0; ; ) { int ch; if (used >=size) { str = myrealloc(str, size += STRBFF); if(!str) return NULL; } ch = getc(stdin); if (ch == EOF || ch == '\n' || ch == '\r') ch = 0; str[used++] = ch; if (!ch) break; } str = myrealloc(str, used); return str; } 

Now, if your compiler supports inlining, the calls to myrealloc () will be replaced by the equivalent of the source code, and the actual function myrealloc () will practically disappear. (check the disassembled output).

+1
source

Source: https://habr.com/ru/post/1432572/


All Articles