1. malloc只是负责申请一块内存,没有任何其他动作。
2. 直接声明结构体或者new 一个结构体指针,会调用默认构造函数。如果结构中包含类,同样会调用成员类的默认构造函数。
3. 程序中的内存错误是因为使用malloc分配一个结构体内存,但是string是一个类。并没有调用string的构造函数,所以string在malloc之后没有正确构造,导致使用时段错误。
---------------------------------------
下面测试程序前两个直接声明结构体和new出来的,都可以正确赋值,但是malloc的那块,赋值就段错误。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout << "construct in A" << endl;
}
};
typedef struct tagTEST
{
A a;
string s;
char* ch;
int i;
} TEST;
int main()
{
TEST t;
t.s = "111";
cout << t.s << endl;
TEST* pNewTest = new TEST;
pNewTest->s = "222";
cout << pNewTest->s << endl;
TEST* pMallocTest = (TEST*)malloc(sizeof(TEST) * 1);
pMallocTest->s = "333";
cout << pMallocTest->s << endl;
return 0;
}