PDA

View Full Version : Problems storing values in structure.


kushalkoolwal
10-19-2004, 06:53 AM
hi,

I have a problem while I am storing the values in the follwoing structure. I have want to store the value 8 in code char data type, 1234 in offset array and test in filename array.
Now after stroing the values in all the 3 variables, whenever I try to print the value of offset it shows me the value stored in offset and also in the filename. In short it appends both the values. For example when I try to print p1.offset it gives me 1234test instead of 1234.

struct req_block
{
char code;
char offset[4];
char filename[4];
};

struct req_block p1;

void main()

{
p1.code=8;
strcpy(p1.offset,"4563");
strcpy(p1.filename="test");
printf("\n%d \n%s \n%s",p1.code,p1.offset,p1.filename);
}

Kindly tell me where I have gone wrong? is there any better way of storing these values in the structure instead of using strcpy. Also when I try to give statement like
p1.offset="1234" it gives me an error. why is it so?

thanks
Kushal

RobSeace
10-19-2004, 01:55 PM
Your main problem is that your buffers are not null-terminated, yet
you treat them as if they are... And, your talk about trying to just
directly assign a string literal to a buffer makes me think you aren't
very familiar with basic C coding rules, and things like the difference
between pointers and arrays/buffers...

Anyway, in short, your strcpy()'s are trashing an extra byte past the
end of each array (meaning, you're writing past the end of your
struct, as a whole, so you're lucky you're not seg-faulting)... They
are writing a null-termination byte, since C strings are always
null-terminated... Yet, you don't give room in your arrays for the
null byte, only for the 4 text chars you copy in... So, your second
strcpy() trashes the null the first one wrote (since, it wrote it on top
of the start of the second buffer), then goes on to trash memory off
the end of the struct itself... And, finally, your printf("%s") of the first
buffer reads past the end and into the second buffer, because the
null char was trashed by that second strcpy(), as mentioned
above, so it keeps going until it hits the null char past the end of
the second buffer... Basically, you either need to increase the
size of your buffers to hold a null char, or NOT try to treat them as
if they're null-terminated strings...

Nope
10-19-2004, 04:49 PM
Or to say it with less words. You always have to make the char arrays one
larger than the text you want to store in as it needs a '\0' to mark its end.
That '\0' or 0 or NULL is automatically copied along with strcpy and sprintf.
It is a commen mistake for starters to forget about that.