12 Окт в 14:14
2 +1
0
Ответы
1

Two problems to watch for:

1) strcpy writes the terminating NUL, so it requires the destination to be large enough. The literal "This is a very long string" is 26 bytes of characters + 1 NUL = 27 bytes. If buf has fewer than 27 bytes, this causes a buffer overflow and undefined behavior andasecurityriskand a security riskandasecurityrisk.

2) strcpy does no bounds checking, so avoid it when you don't know the destination size.

Safer alternatives pickonedependingonyourplatformandneedspick one depending on your platform and needspickonedependingonyourplatformandneeds:

If buf is an array and you know its size at compile time:
char buf[sizeof "This is a very long string"];
strcpy(buf, "This is a very long string"); // safe because sizes match

Prefer snprintf standardandsimplestandard and simplestandardandsimple:
char buf100100100;
snprintf(buf, sizeof buf, "%s", "This is a very long string");

Use strlcpy if available BSDandmanysystemsBSD and many systemsBSDandmanysystems:
char buf100100100;
strlcpy(buf, "This is a very long string", sizeof buf);

If you must use strncpy, ensure NUL termination:
char buf100100100;
strncpy(buf, "This is a very long string", sizeof buf - 1);
bufsizeofbuf−1sizeof buf - 1sizeofbuf1 = '\0';

Dynamically allocate exactly what you need:
const char s = "This is a very long string";
char buf = mallocstrlen(s)+1strlen(s) + 1strlen(s)+1;
if bufbufbuf { strcpybuf,sbuf, sbuf,s; / ... / freebufbufbuf; }

If buf is just a pointer and you don't know its capacity, don't use strcpy — either pass the buffer size into the function or allocate the destination yourself.

Want me to show a fixed version for your specific code? If so, tell me how buf is declared sizeorpointersize or pointersizeorpointer.

12 Окт в 14:53
Не можешь разобраться в этой теме?
Обратись за помощью к экспертам
Гарантированные бесплатные доработки в течение 1 года
Быстрое выполнение от 2 часов
Проверка работы на плагиат
Поможем написать учебную работу
Прямой эфир