LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   C++ and Valgrind: Can't understand "Invalid read" error (https://www.linuxquestions.org/questions/programming-9/c-and-valgrind-cant-understand-invalid-read-error-828414/)

errigour 10-04-2012 07:47 AM

struct areas *top = NULL;
top = malloc(sizeof (top));

someone told me to make sure it's
top = malloc(sizeof(struct areas));

sorry I posted here.

johnsfine 10-04-2012 07:58 AM

Quote:

Originally Posted by errigour (Post 4795598)

I'm still curious about what you meant in posting the above link.

There is one link to source code on that page and that source code uses the name "top" in a conceptually similar way to what is probably in the program you are debugging. But neither the bug you just described
Code:

top = malloc(sizeof (top));
nor the strange Valgrind symptom you described earlier
Code:

if ( top== NULL)
correspond to anything in that source code.

Now that you posted the source code of the bug, it was easy to identify your other thread, containing a better discussion of that bug:
http://www.linuxquestions.org/questi...ed-4175430177/

Looking at just your post directly above this (before finding your other thread) I was tempted to make the same suggestion as appears at the bottom of the reply you already got here:
http://www.linuxquestions.org/questi...7/#post4795948

That can be a cleaner approach in complicated projects, because it avoids putting information, (the struct name) that might be changed in subsequent program revisions, in a place where the compiler could not see the bug if you made such a change in one place but not the other.

You should understand sizeof(*top) is not computed at run time and is not the size of the actual object top points to (which might be NULL). It is computed at compile time and is the size of the kind of object that top should point to.

sizeof(top) is the size of the pointer, not the size of what it does and/or should point to.


All times are GMT -5. The time now is 06:35 PM.