Question

I decompiled a application and I don't know the real array size so I made it pretty big but I wonder do I need to make exactly what I know it's going to be before the strcpy is used or must I consider the size of the strcpy as well?

signed int __cdecl SendSomePacket(struct CONNECTION* conn, int a1, int a2, const char *a3)
{
  //char buf[256]; // [sp+10h] [bp-9h]@1
  char buf[10]; // [sp+10h] [bp-9h]@1

  *(unsigned int *)&buf[1] = a1;
  *(unsigned int *)&buf[5] = a2;
  strcpy(&buf[9], a3);
  buf[0] = 0xEu;                                // Packet Type
  return SendPacket(CONNECTION->socket, buf, strlen(a3) + 10, 1);
}

I ask should I leave it with 256 which is the default size it guesses by which is always multiplies of 2 like 256,512,1024,2048..

char buf[256]; // [sp+10h] [bp-9h]@1

or should I make it as small as possible to save memory.

char buf[10]; // [sp+10h] [bp-9h]@1

which I figured after the strlen(a3) that number is how big the buffer should be.

I tried just strcpy with a buffer size of 10.. and I put in a string thats over 500 in length and it worked maybe just got lucky. I just wanted to know should I make the static buffer large enough for the initial packet + the data from the strcpy or just for the packet alone? and the packet gets appended probably anyways.

Here is a example I tried.

http://ideone.com/w7DsCl

Was it helpful?

Solution

It will copy as many characters as there are in the source string. It has no idea how large the destination buffer is, and will overwrite into random territory if you're giving it a too long source string. There is no "default size" and absolutely no "guessing" involved.

Be careful, it sounds as if you're not very clear on how the basics work here.

If you know the length of the source already, it's better to use memcpy().

OTHER TIPS

strcpy will write as many byes as length of source string so it will go beyond your buffer size. so it is preferred to use bigger size array or to use dynamic memory allocation.

I think it is better if you use dynamic memory allocation using malloc.

Do this:

char *buf = malloc(strlen(s3) + 1 + sizeof(a1) + sizeof(a2));

then

sprintf(buf, "%u%u", a1, a2);
strcpy(buf + 8, a3); // Assuming sizeof(u_int) == 4

It will be memory efficient.

Do remember to free the buf after use.

A lot of the confused criticism about strcpy() being an unsafe function comes from using it like this.

Before any call to strcpy(), you need to know the size of the data to be copied. If you don't know this in advance, you must call strlen() to find out, before calling strcpy(). Otherwise your program is vulnerable to buffer overflows.

If you do know the size, strcpy() is however perfectly safe to use.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top