读书人

用malloc分配内存后用memcpy将字符串

发布时间: 2013-10-21 17:02:52 作者: rapoo

用malloc分配内存后,用memcpy将字符串复制进去
如题,用malloc 分配内存后,用memcpy 将字符串复制进去。若用字符数组指明长度就不会错。而用malloc则提示“Segmentation Fault - core dumped”(在ubuntu中运行)

#include"memory.h"
#include"stdio.h"
#include"string.h"

char d[30];
memcpy(d,s,sizeof(s)+1);
sprintf("%s",d);

return 0;
}*/

int main()
{char *s="asdgsadggh";
//char d[30]; 用字符数组就不会错
char *d=(char*)malloc(sizeof(char)*(1+strlen(s)));
memcpy(d,s,strlen(s)+1);
printf("%s",d);
return 0;

}

请高手指点!谢谢!

[解决办法]

探讨
如题,用malloc 分配内存后,用memcpy 将字符串复制进去。若用字符数组指明长度就不会错。而用malloc则提示“Segmentation Fault - core dumped”(在ubuntu中运行)

#include"memory.h"
#include"stdio.h"
#include"string.h"

char d[30];
memcpy(d……

[解决办法]
只需要#include"stdlib.h"即可,另外这里最好用strcpy(d,s):
C/C++ code
#include"memory.h"#include"stdio.h"#include"string.h"#include"stdlib.h"int main(){char *s="asdgsadggh";char *d=(char*)malloc(sizeof(char)*(1+strlen(s)));memcpy(d,s,strlen(s)+1);//strcpy(d,s);printf("%s\n",d);return 0;} 

读书人网 >C++

热点推荐