|
From: Brian B. <bri...@gm...> - 2013-02-11 06:55:12
|
On Sun, Feb 10, 2013 at 9:55 PM, David Hourn (DTH Design)
<dt...@dt...> wrote:
> I am new to C and Valgrind, so I can't understand why I am getting an error
> message on what seems like a pretty standard if statement.
>
> Basically I want to strip the newline character, '\n', from the value fgets
> returns to me. Pretty much everywhere I could find said the recommended way
> to do this was something like this: (getInput is a function I have written
> where fgets resides and it does some validation)
>
> char *getInputNoNewline(int max, char message[]) { static char* input; int
> maxchars = max+ADDCHARS input = (char*)malloc(maxchars); input =
> getInput(max, message); if (input[strlen(input) - 1] == '\n') {
> input[strlen(input) - 1] = '\0'; } return input; }
Hi David -
First you assign a malloced address to input, and then on the
following line, you assign to input from getInput. At the very least,
you should be leaking memory there. My guess (only a guess, since we
don't have the code for getInput), is that getInput does not provide a
valid null-terminated string for strlen, which is why there are
invalid reads when calling strlen.
Brian
|