Yogesh wrote:
Hi all,
Please look at the code below:
int main (int argc, char * const argv[])
{
int * i = (int *)malloc(sizeof(int));
*i = 50;
int &badref = *i;
printf("%d\n",badref);
delete i;
printf("%d\n",badref);
//This reference is bad coz "i" is deleted
badref = 70;
printf("%d\n",badref);
return 0 ;
}
It's not C++, but tools like valgrind can catch many of these errors. For
example:
g++ -Wall badref.cpp -g -o badref
valgrind badref
==11523== Memcheck, a memory error detector for x86-linux.
==11523== Copyright (C) 2002-2005, and GNU GPL'd, by Julian Seward et al.
==11523== Using valgrind-2.4.0, a program supervision framework for
x86-linux.
==11523== Copyright (C) 2000-2005, and GNU GPL'd, by Julian Seward et al.
==11523== For more details, rerun with: -v
==11523==
50
==11523== Mismatched free() / delete / delete []
==11523== at 0x1B9098CF: operator delete(void*) (vg_replace_malloc.c:155)
==11523== by 0x8048513: main (badref.cpp:10)
==11523== Address 0x1B92F028 is 0 bytes inside a block of size 4 alloc'd
==11523== at 0x1B909222: malloc (vg_replace_malloc.c:130)
==11523== by 0x80484DD: main (badref.cpp:6)
==11523==
==11523== Invalid read of size 4
==11523== at 0x804851A: main (badref.cpp:11)
==11523== Address 0x1B92F028 is 0 bytes inside a block of size 4 free'd
==11523== at 0x1B9098CF: operator delete(void*) (vg_replace_malloc.c:155)
==11523== by 0x8048513: main (badref.cpp:10)
50
==11523==
==11523== Invalid write of size 4
==11523== at 0x8048530: main (badref.cpp:13)
==11523== Address 0x1B92F028 is 0 bytes inside a block of size 4 free'd
==11523== at 0x1B9098CF: operator delete(void*) (vg_replace_malloc.c:155)
==11523== by 0x8048513: main (badref.cpp:10)
==11523==
==11523== Invalid read of size 4
==11523== at 0x8048539: main (badref.cpp:14)
==11523== Address 0x1B92F028 is 0 bytes inside a block of size 4 free'd
==11523== at 0x1B9098CF: operator delete(void*) (vg_replace_malloc.c:155)
==11523== by 0x8048513: main (badref.cpp:10)
70
==11523==
==11523== ERROR SUMMARY: 4 errors from 4 contexts (suppressed: 16 from 1)
==11523== malloc/free: in use at exit: 0 bytes in 0 blocks.
==11523== malloc/free: 1 allocs, 1 frees, 4 bytes allocated.
==11523== For counts of detected errors, rerun with: -v
==11523== No malloc'd blocks -- no leaks are possible.
Such tools can't catch everything (like casting a pointer as a pointer to an
unrelated type), but they're better than nothing.
--
Al Dunstan, Software Engineer
OptiMetrics, Inc.
3115 Professional Drive
Ann Arbor, MI 48104-5131