Hi friends i am getting this error whwn i am running my code "glibc detected * free() invalid pointer" in my code i am creating 3 pointer and allocating memory to only one using new and deleting all the three pointer.
class test()
{
public :
int a;
/..some functionality../
};
class second_test()
{
public :
int b;
/..some functionality../
}
class third_test()
{
public :
int c;
/..some functionality../
}
int main()
{
test *ptrtest;
second_test *psecond_test;
third_test*pthird_test;
ptrtest = new test;
/..Doing some functionality.../
delete ptrtest;
delete psecond_test;
delete pthird_test;
}
and when i am running it is giving above error but surprisingly not al the time it is giving error 7 out nof 10 time it gives above error..please help me what exactly the problem. BECAUSE in c++ i think it is safe to delete NULL pointer.
second_test *psecond_test;
That does not point to a null pointer.
second_test *psecond_test = NULL;
That does.
As an example, here's some code:
#include <cstdio>
int main() {
struct x *ptr;
printf("%p\n", ptr);
}
And when I run it, I get different addresses each time. (Although they could be the same, they could be zero, it's undefined what they are)
[10:36pm] ./foo
0x7fff6413205e
[10:36pm] ./foo
0x7fff6cff105e
[10:36pm] ./foo
0x7fff6890305e
Clang, for example, warns about this when I use -Wall
.
[10:41pm] clang++ -Wall foo.cc
foo.cc:5:9: warning: variable 'ptr' is uninitialized when used here [-Wuninitialized]
delete ptr;
^~~
foo.cc:4:10: note: initialize the variable 'ptr' to silence this warning
int *ptr;
^
= NULL
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.