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;
re开发者_如何学运维turn 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 e.g.,
snprintf(iD, sizeof(iD), "%i%s", iPrefix, staticChar);
char* prefix;
//some code
sprintf(prefix, "%i", iPrefix);
You forgot to assign some memory to prefix
.
no memory has been allocated to prefix. so it can access any memory location which which generates segmentation fault , in simple words.
精彩评论