Originally posted by blizunt7
sprintf(next,"%d",nextItem); // convert from int to char
A segmentation fault is generated when you write to an area of memory that doesn't belong to your program.
When you declare a primative (i.e.
non-object) variable, such as next, it can contains any value until the point where it is assigned to. That's why it's always a good idea to initialise your variables.
is not initialised here; it could point to anywhere in your memory address space. You then attempt to write to that location (which you don't know where it is), which is probably not available to your program, causing a segmentation fault.
The C++ compiler that comes with GCC will issue a warning about this if you use the -Wall
option, which is usually a good idea.
You could fix this using
, where N
is defined as a number big enough to hold any int in a string, plus a leading whitespace character. This value will vary between computers, so that's not a good solution. Also, the way that numbers are formatted varies from country to country (the British use comma as a thousands-seperator whereas the French use it as a decimal point).
This is not the easiest way to write a number to a stream (or a string); you probably want to look at the std::num_put
class defined in <locale>
; this can be used to write numbers to a stringstream if you like.