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);
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?
source share