C + + foundation — pointer field pointer and free

Time:2021-8-31

Repeated release of wild pointer

Recently, a problem has been found. After a pointer is released twice, if it is not empty in the middle, an invalid address specified to rtlvalidateheap invalid heap address error will be reported.

#include 
#include 
#include 

using namespace std;
int main() {
	int* p = (int*)malloc(100);
	free(p);
	free(p);
}

To figure out why this error occurred, you must first figure out what free() did:

#include 

using namespace std;

int main() {
 	
	int *p = (int*)malloc(100);
	Printf ("address of P before release% P \ n", P); 
	free(p); 
	Printf ("address of P after release% P \ n", P); 
	/**The result is:
	Address before P release 00000000006ffe14
	Address after P release 00000000006ffe14 
	**/
}

As you can see from the code, the value of P before and after free () does not actually change, that is, P is not set to null.

If this statement is added at this time:

char x = *p;

The program breakpoint invalid address specified to rtlvalidateheap is triggered

However, when p is pointed, why is it an invalid heap address?

The reason is that the free () function only tells the operating system that I no longer use this memory, and the operating system can reallocate this memory.

Back to the original problem, when p is free () once, it actually becomes a wild pointer to an area protected by the operating system, which may be pointed to by other pointers in the future. Therefore, the second time we free (P), it is actually operating a space that may have been used by other modules. At this time, we start invalid address specified to rtlvalidateheap.

Recommended Today

Java Engineer Interview Questions

The content covers: Java, mybatis, zookeeper, Dubbo, elasticsearch, memcached, redis, mysql, spring, spring boot, springcloud, rabbitmq, Kafka, Linux, etcMybatis interview questions1. What is mybatis?1. Mybatis is a semi ORM (object relational mapping) framework. It encapsulates JDBC internally. During development, you only need to pay attention to the SQL statement itself, and you don’t need to […]