用strcpy()出错。用strdup()就对了!
#include<iostream>
#include<string>
using namespace std;
struct a
{
char *b;
int c;
};
void main()
{
a *m;
m=(a *)malloc(sizeof(a));
free(m->b);
m->b=strdup("afsa");
/*strcpy(m->b,"fafe");*/
}
[解决办法]
free(m->b)后,m->b为野指针,需要申请内存。
strdup函数中的返回的指针指向的内存是strdup内部申请的内存。不用时应该free,否则内存泄漏。
strcpy不会替你分配内存,需要程序员自行申请。
使用strcpy改为以下的就OK:
const char* str = "afsa";
m->b = (char*)malloc(strlen(str) + 1);
strcpy(m->b, str);
[解决办法]
可能是因为m->b没有分配内存吧,strcpy的目的指针一定要是已经分配内存的指针。
[解决办法]
可以结贴了,没有任何悬念!!
[解决办法]
The _strdup function calls malloc to allocate storage space for a copy of strSource and then copies strSource to the allocated space.
[解决办法]