Size 1 reading deemed invalid by Valgrind

The “recently” is mentioned because valgrind keeps track of freed memory for a limited number of frees, so it can’t say for sure that it wasn’t freed a million frees back – in this case it wasn’t, but if you see a message like that, it MAY be that it has become invalid because it was freed ages ago. Question:
I am getting this output when using valgrind:
Here is where I have narrowed it down to being the problem in my code:
I have many errors, and providing the entire valgrind output would be overkill I feel.


Valgrind is causing me trouble with my program, specifically in the main part where errors occur.

int main()
char comanda[N];
char *p;
while( fgets(comanda,100,stdin)!=NULL)
    p=strtok(comanda," n");
    if (strcmp(comanda,"INIT")==0)
        p=strtok(NULL," ");
395 >>if (strcmp(p,"DUMP")==0)
    if (strcmp(p,"ALLOC")==0)
    ....return 0;}

And when i run valgrind it says:

Invalid read of size 1
at 0x401569: main (:395)
Address 0x0 is not stack'd malloc'd or (recently) free'd

I am unable to determine the issue with this program.

Solution 1:

How to read this:

Invalid read
of size 1

Your software is attempting to access a location that Valgrind disapproves of when trying to read a single byte.

at 0x401569: main (:395)

The location of this occurrence in the code is evident as strcmp has been clearly inlined.

Address 0x0
does not fall under the category of
stack’d malloc’d
or has not been categorized as

The memory address being read as 0x0 indicates it’s “NULL”. The remaining part of the statement explains why it’s an invalid address. It’s neither from the stack nor has it been allocated using malloc. Furthermore, it hasn’t been freed recently. The word “recently” is mentioned because valgrind only tracks freed memory for a limited number of times, so it’s not certain that it wasn’t freed a long time ago. However, in this case, it hasn’t been freed. It’s worth noting that the address wouldn’t be zero or close to zero.

Solution 2:

When there are no more tokens remaining,


could potentially yield a NULL result.

If you provide NULL as an argument to


, you will encounter undefined behavior due to dereferencing NULL.

Frequently Asked Questions