getline throwing uninitialized value in valgrind
Relavant code.
Code:
#include <stdio.h> Code:
char * getline_mem_alloc(FILE * file) Code:
char * allocate_string_mem(const char * str) Code:
valgrind -s --leak-check=full --track-origins=yes ./a.out |
Code:
char * allocate_string_mem(const char * str) |
Valgrind knows the memory has been allocated within getline() and assigned to pointer buffer, but seems unaware that it has been written by getline(). Any attempt to read it produces a valgrind error, but you can write to it and once you do the program completes and valgrind says all is OK. For example, add strcpy(buffer,"some text") immediately after the call to getline() (be sure not to exceed buflen).
I am not a frequent valgrind user so cannot say whether this is to be expected or why it happens. My searches turned up other odd valgrind behaviors with getline, some version dependent, but not this exactly. Hope it helps. |
Ok. I tried a few more things. And I dumped those 2 alloc functions I had written and replaced with strdup in my library.
Thank you both. It works fine if I don't try to operate on the tempbuf return. No errors. But as soon as I want to run an operation on it, strlen or whatever so far seems to toss that error. |
It might give more information, if you compile your shared library with option `-g`.
Or for debugging you could directly link your rutins into the executable. PS: don't do this with 'buflen': Code:
buflen = getline(&buffer, &buflen, file); |
Ok done. The main function is just me fiddling around. I normally run tests on file ops. I did replace that buflen thing with a test with error message & bail out on fail.
|
E.g.:
Code:
ssize_t strLen = getline(&buffer, &buflen, file); |
Could not get this off my mind as I did not really understand it on first look, and knew it, and it did not seem reasonable that valgrind would miss an initialization.
NevemTeve is on the right track. You need to test for unsuccessful call to getline(...), it returns -1 for both errors and for EOF, and it is the EOF that is causing the problem. You are not using buflen or the returned character count, so just test for -1. The acual cause of the valgrind error is, even though unsuccessful or EOF, a buffer will have been allocated and needs to be free()d and not further used. So, along with the change from allocate_string_mem() to strdup() and a test of returned pointer, this should fix it up properly: Code:
char * getline_mem_alloc(FILE * file) |
Git pushed. I am very grateful to you folks. Works no errors now.
*EDIT* in a previous post I mentioned about needing to research return codes. its getting more necessary quickly. |
You are very welcome, and thanks for the opportunity to improve my poor valgrind skills!
|
All times are GMT -5. The time now is 03:01 PM. |