用strcpy()出错。用strdup()就对了!该怎么处理
用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.
------解决方案--------------------
------解决方案--------------------
b只是一个指针,并没有为指向的内容分配空间,这样会更好理解:
m->b="afsa";
#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.
------解决方案--------------------
------解决方案--------------------
b只是一个指针,并没有为指向的内容分配空间,这样会更好理解:
m->b="afsa";