Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Valgrind: Invalid read of size 1

Tags:

I'm having an issue with valgrind: This is my program (well the main part where the errors appear):

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," ");         Init(n);                 } 395 >>if (strcmp(p,"DUMP")==0)         {         Dump(n);}     if (strcmp(p,"ALLOC")==0)         {         Alloc(j,n);         }     ....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 can't figure out what's the matter with this program.

like image 219
user1934103 Avatar asked Dec 28 '12 09:12

user1934103


People also ask

What does invalid read mean Valgrind?

An Invalid read means that the memory location that the process was trying to read is outside of the memory addresses that are available to the process. size 8 means that the process was trying to read 8 bytes. On 64-bit platforms this could be a pointer, but also for example a long int.

What is invalid read of size 4 in C?

Error message: Invalid write of size 4, means possible an integer or pointer on 32bits platform was stored in a memory that is not allocated with malloc() or on the stack. This happened at example. c 6th line, that was called from main.

What do valgrind errors mean?

Valgrind prints this warning when an unusually large memory region is allocated, on suspicion that the size may be so large due to an error. If the intention of your code was to allocate a large block, then all is well.


1 Answers

How to read this:

Invalid read of size 1

Your program is trying to read one byte from somewhere that Valgrind doesn't like.

at 0x401569: main (:395)

Where in the code this happens (clearly strcmp has been inlined)

Address 0x0 is not stack'd malloc'd or (recently) free'd

What the address it was reading - 0x0 is "NULL". The rest of the statement just says why it's invalid (it's not from the stack, it's not something you've got from malloc, and not been freed recently). 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. The address would not be zero tho' (or near zero).

like image 130
Mats Petersson Avatar answered Oct 05 '22 14:10

Mats Petersson