Windows下MinGW与MSVC2015关于char指针的区别

话不多说,直接上代码。

#include<iostream>
#include<string.h>
#include<stdlib.h>
using namespace std;
void test11(int* p)
{
	(*p) = 5;
}
void test1()
{
	int a = 6;
	int* p = &a;
	cout << (*p) << endl;
	cout << a << endl;
	test11(p);
	cout << (*p) << endl;
	cout << a << endl;
}
void test22(char* s)
{
	free(s);
	s = (char*)malloc(15);
	memcpy(s, "1234567890", 10);
}
void test2(char* &s)
{
	free(s);
	s = (char*)malloc(15);
	memcpy(s, "1234567890", 10);
}
int main()
{
	char* s;
	s = (char*)malloc(11);
	memcpy(s, "helloworld", 10);
	cout << s << endl;
	test22(s);
	cout << s << endl;
	while (1);
}

  关于整形指针的调用(不涉及空间的重新分配),两个编译器并没有明显的区别。

但是关于char* 指针,运行结果就截然不同。

下图为mingw下的运行结果:

下图为msvc下test22()的运行结果。

下图为msvc下test2()的运行结果。

void test22_equal(char* s)
{
	char* str = s;
	free(str);
	str = (char*)malloc(15);
	memcpy(str, "1234567890", 10);
}

  运行结果的差异,推测代码的实际效果如上所示。

只是普通的char*指针,msvc自动优化成了一个类似局部变量的效果,所以test22()里面可以释放掉main里面的s,但是不能再重新为其分配空间。

原文地址:https://www.cnblogs.com/dayq/p/15733074.html