简体   繁体   中英

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 .

no memory has been allocated to prefix. so it can access any memory location which which generates segmentation fault , in simple words.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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