Reputation: 111
I am trying to update a call to strcpy
with the more secure strcpy_s
. The old function call looks like this:
char buf[6];
strcpy(buf+1, "%#c");
In order to turn the above code into the more secure version, what would I put in for the size parameter?
char buf[6];
strcpy_s(buf+1, /*SIZE GOES HERE*/, "%#c");
I suppose I am getting confused with the buf+1
portion of the code. Is that essentially just a pointer that points to the register ONE block over from buf
? If so, what would I put in for the SIZE parameter of strcpy_s
? I have tried:
strcpy_s(buf+1, sizeof(buf+1), "%#c");
which seems to work, but I wonder if there is a better way to do it.
Upvotes: 1
Views: 466
Reputation: 238351
The size should be 5
(assuming you want to skip the first index). A proper way to calculate is:
int offset = 1; // not necessary, but shows the connection between the size and offset
strcpy_s(buf+offset, (sizeof(buf)-offset) / sizeof(buf[0]), "%#c");
Division by char size is redundant, but it's good to remember because it's necessary if you use a wide characters.
Upvotes: 1
Reputation: 7625
buf+1
points to the memory location one past the starting address of buf
, so effectively the copy starts from that location. But the size
parameter specifies the size of the destination. It does not make sense to use sizeof(buf+1)
for that parameter. You should pass the available space of the destination ( should be <= (total size - starting offset)).
In your case, it should be
strcpy_s(buf+1, sizeof(buf)/sizeof(*buf) - 1, "%#c");
Upvotes: 0
Reputation: 36438
If you were copying into the start of buf
, you'd say:
strcpy_s(buf, sizeof(buf), "%#c");
since you're skipping the first character, you have one less character to work with, so:
strcpy_s(buf + 1, sizeof(buf) - 1, "%#c");
Upvotes: 5