简体   繁体   English

返回之前的分段错误

[英]Segmentation fault before return

Why does the following code seg fault before returning: 为什么在返回之前以下代码段错误:

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;
}

At the minute, the cout will display, but I get a segmentation fault. 此刻将显示提示,但出现分段错误。

You need to allocate memory for prefix before calling this: 您需要在调用此之前为前缀分配内存:

sprintf(prefix, "%i", iPrefix);

or you could refactor the code eg, 或者您可以重构代码,例如,

snprintf(iD, sizeof(iD), "%i%s", iPrefix, staticChar);
char* prefix;
//some code

sprintf(prefix, "%i", iPrefix);

You forgot to assign some memory to prefix . 您忘记为prefix分配一些内存。

no memory has been allocated to prefix. 没有为前缀分配内存。 so it can access any memory location which which generates segmentation fault , in simple words. 因此,它可以简单地访问任何会产生分段错误的内存位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM