C question - Overwriting

Soldato
Joined
22 Oct 2005
Posts
2,883
Location
Moving...
I've got two globally declared strings:
Code:
char locations[5][25];
char speedString[25];
I set the locations string first by filling it with data from a txt file using: (temp being a local string declared like char temp[25])
Code:
locations[count][end] = temp[end];

I then set the speedSting using
Code:
sprintf (speedString, "Speed: %3d kmh", curSpeed);


When setting the speedString, not only does it fill the speedString (correctly) but it also overwrites parts of the locations string.

Any ideas as to why this is happening? It's really doing my head in because I cant see why it is doing it. There are other functions before and after this problem area setting strings fine :confused:

Thanks for any help.
 
Weird, Have you tried memset(speedString,'\0',strlen(speedString)); sometime before you sprintf it. I don't think this is the problem... worth trying :)

You prolly want to use str(n)cpy / strdup to copy strings as well.. Otherwise your just changing the pointer, which may or may not be what you want.
 
Last edited:
As una says, strncpy is the proper and safest way to do what your trying to do. An even better solution would be to malloc a block of memory for what your trying to do to reserve it for use only by the variable it was set up for. This will protect you against the memory trampling problem your having. Just remember to free when your done with the memory.
 
Back
Top Bottom