[英]C++ strcpy_s throws error when copying to new char array
我的目標是生成一個具有正確數量斑點的新數組,並將一個舊的字符數組復制到其中。
使用strcpy_s時,將引發異常。 我無法弄清楚為什么會引發異常,該異常指出Buffer太小。 我不能使用向量或字符串。 如何使用strcpy_s和char數組解決此問題?
char str[4] = { 't', 'e', 's', 't' };
int allocated = 4;
char * reservedString = new char[allocated]();
strcpy_s(reservedString, allocated, str);
編輯:更改我的代碼以將一個添加到數組給我相同的“緩沖區太小”異常。
char str[4] = { 't', 'e', 's', 't' };
int allocated = 4;
char * reservedString = new char[allocated+1]();
strcpy_s(reservedString, allocated, str);
編輯2:正如有人評論,str需要設置為5大小,並包含一個空終止符。 謝謝你,這解決了我的問題。
更新的代碼:
char str[5] = { 't', 'e', 's', 't', '\0'};
int allocated = 5;
char * reservedString = new char[allocated]();
strcpy_s(reservedString, allocated, str);
char str[4] = { 't', 'e', 's', 't' };
是內存中的4字節數組。 它不是字符串,並且完全是隨機的,在這4個字節之后將出現“尾隨”零,並且在兩者之間還有任意數量的其他數據。
但是, strcpy_s()
希望復制一個以零結尾的字符串,它只是檢查源字符串是否適合目標字符串的附加功能之一。 不會,這就是為什么會出現錯誤。
[...]在運行時檢測到以下錯誤,並調用當前安裝的約束處理程序函數:
* src或dest是空指針
* destsz為零或大於RSIZE_MAX
* destsz小於或等於strnlen_s(src,destsz); 換句話說,將發生截斷
*源字符串和目標字符串之間會發生重疊
您得到第三個,“垃圾”字節將被截斷。
您需要五個字符來存儲以零結尾的字符串"test"
。 您的str
數組只有四個字符,沒有零終止符。 如果需要零終止符,請這樣聲明:
char str[] = "test";
那你當然需要
int allocated = 5;
在那之后:
char * reservedString = new char[allocated];
strcpy_s(reservedString, allocated, str);
str
不是字符串 。 字符串是由NUL終止的非NUL字符序列。
您應該將緩沖區的大小傳遞給strcpy_s()
,而不是最大字符串大小(少一)。
也就是說,如果你要使用strcpy_s()
在所有 。 你不應該
使用strcpy()
,或者因為已經有了確切的大小,使用memcpy()
或std::copy_n()
。
附帶說明一下,將內存歸零只是為了轉過來並覆蓋它是毫無意義的浪費。
您沒有分配適當的內存:
char str[4] = { 't', 'e', 's', 't' };
它分配5個字節,每個字符分配4個字節,再加上空終止符。-
做:
char str[4] = { 't', 'e', 's', 't' };
char * reservedString = new char[5]();
strcpy_s(reservedString, allocated, str);
要么:
char str[4] = { 't', 'e', 's', 't' };
char * reservedString = new char[5]();
strcpy(reservedString, str);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.