[英]strcat function still works when destination string array is too small
我必須為家庭作業重新創建一堆字符串函數。
#include <stdio.h>
#include <string.h>
char *strcat1(char *s1, const char *s2);
int main(void)
{
char string[4] = "asd";
char string1[4] = "asd";
char string2[] = "teststring";
printf("%s\n", strcat(string, string2));
printf("%s\n", strcat1(string1, string2));
}
char *strcat1(char *s1, const char *s2)
{
size_t a=0;
for(a;s1[a]!='\0';a++)
{
}
size_t b=0;
for(b;s2[b]!='\0';a++,b++)
{
s1[a]=s2[b];
}
s1[a]=s2[b];
return s1;
}
output 是:
asdteststring
asdteststring
string
和string1
可以容納 3 個字符 + \0,所以在s1[a]
a
的 a 通過 3 后它不應該失敗嗎? 為什么它仍然有效? 我在重新創建 strcpy 時遇到了同樣的事情。
您的代碼表現出未定義的行為(UB) ,因為正如您所說,您的目標緩沖區不足以容納字符串。 因此,您不滿足您使用的庫 function 的要求。 UB 並不意味着程序一定會崩潰,而是意味着它可能會崩潰。
在這種情況下不會發生這種情況的原因是因為您分配的緩沖區位於組織為堆棧的 memory 部分上。 因此,存在緩沖區末尾的 memory。 它只是不屬於您認為它所屬的變量。
事實上,如果你用-fsanitize=address
編譯你的程序,你會看到strcat
實際上會導致緩沖區溢出:
=================================================================
==16978==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7ffd3f946594 at pc 0x7ff2aec575f3 bp 0x7ffd3f946560 sp 0x7ffd3f945d10
WRITE of size 11 at 0x7ffd3f946594 thread T0
#0 0x7ff2aec575f2 in __interceptor_strcat (/usr/lib/x86_64-linux-gnu/libasan.so.5+0xa95f2)
#1 0x5638a1480330 in main (/tmp/_/a.out+0x1330)
#2 0x7ff2aea11e0a in __libc_start_main ../csu/libc-start.c:308
#3 0x5638a14800f9 in _start (/tmp/_/a.out+0x10f9)
Address 0x7ffd3f946594 is located in stack of thread T0 at offset 36 in frame
#0 0x5638a14801c4 in main (/tmp/_/a.out+0x11c4)
This frame has 3 object(s):
[32, 36) 'string' (line 6) <== Memory access at offset 36 overflows this variable
[48, 52) 'string1' (line 7)
[64, 75) 'string2' (line 8)
所以,在這個診斷之后,如果我打印string
,我會得到這個:
字符串
分段故障
雖然string
仍然應該是asd
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.