views:

192

answers:

3

Hi,

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.

+8  A: 

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);
Tuomas Pelkonen
snprintf did the job. Perfect..
donalmg
+2  A: 
char* prefix;
//some code

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

You forgot to assign some memory to prefix.

N 1.1
+1  A: 

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

CadetNumber1