don*_*lmg 1 c++ segmentation-fault
为什么以下代码在返回之前出错:
int main()
{
char iD[20];
memset (iD, 0, 20);
char* prefix;
srand (time(NULL) );
int iPrefix = rand()%1000000;
sprintf(prefix, "%i", iPrefix);
int len = strlen(prefix);
char* staticChar = "123456789";
//set prefix into ID
memcpy(iD, prefix, len);
// append static value
memcpy(iD+len, staticChar, 20-len);
cout << "END " << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在那一刻,cout会显示,但是我遇到了分段错误.
在调用之前,您需要为前缀分配内存:
sprintf(prefix, "%i", iPrefix);
Run Code Online (Sandbox Code Playgroud)
或者你可以重构代码,例如,
snprintf(iD, sizeof(iD), "%i%s", iPrefix, staticChar);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
762 次 |
| 最近记录: |