Pointer overlay will constantly change the pointer point

Insert picture description here

The following is a demonstration of the wrong code:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void test()
{
    
    
	//指针叠加会不断改变指针指向
	//指针p一开始指向堆区开辟内存的首地址
	char* p = (char*)malloc(sizeof(char)*20);
	char buf[] = "hello";
	int len = strlen(buf); //包含\0
	for (int i = 0; i < len; i++)
	{
    
    
		//每次循环都会在堆区开辟的内存从内存首地址开始往后连续存储,指针p的指向也在不断改变
		*p = buf[i];
		//指针p每次+1,是根据char类型推导出每次加上一个字节的长度
		p++;//修改原来指针的指向
	}
	if (p != NULL)
		free(p);//会报错
}
int main()
{
    
    
	test();
	return 0;
}

Insert picture description here
Solution: Create a temporary pointer to manipulate memory to prevent errors

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void test()
{
    
    
	//指针叠加会不断改变指针指向
	//指针p一开始指向堆区开辟内存的首地址
	char* p = (char*)malloc(sizeof(char)*20);
	char buf[10] = "hello";
	int len=strlen(buf); //包含\0
	//解决方法:创建临时指针操作内存,防止出错
	char* pp = p;
	for (int i = 0; i < len; i++)
	{
    
    
		//每次循环都会在堆区开辟的内存从内存首地址开始往后连续存储,指针p的指向也在不断改变
		*pp = buf[i];
		//指针p每次+1,是根据char类型推导出每次加上一个字节的长度
		pp++;//修改原来指针的指向
	}
	if (p != NULL)
	{
    
    
		free(p);
		p = NULL;
		pp = NULL;
	}

}
int main()
{
    
    
	test();
	return 0;
}

Insert picture description here

Guess you like

Origin blog.csdn.net/m0_53157173/article/details/113988051