[英]How to copy a malloced string into another string in C
我有這個隨機生成字符串的 function
char *generate_random_string(int seed) {
if (seed != 0) {
srand(seed);
}
char *alpha_num_str =
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789";
char *random_str = malloc(RAND_STR_LEN);
for (int i = 0; i < RAND_STR_LEN; i++) {
random_str[i] = alpha_num_str[rand() % (strlen(alpha_num_str) - 1)];
}
return random_str;
}
我想復制這個 function 的返回值,如果我給它一個種子 '1' 到一個名為initialisation_vector
的字符串中,這就是我目前的做法:
char initialisation_vector[RAND_STR_LEN + 1] = {0};
strcpy(initialisation_vector, generate_random_string(1));
但是,當我運行代碼時,我從strcpy
行收到malloc
緩沖區溢出錯誤。 我做錯了什么,如何為此分配足夠的 memory ?
主要問題:
字符串為 C 預計為空/零終止。 這意味着一個n
字符串應該分配有n+1
個字節,最后一個應該是'\0'
。
您的代碼中的問題是random_str
被分配為恰好包含RAND_STR_LEN
字符,因此錯過了 null 終止。
你應該改變:
char *random_str = malloc(RAND_STR_LEN);
for (int i = 0; i < RAND_STR_LEN; i++) {
random_str[i] = alpha_num_str[rand() % (strlen(alpha_num_str) - 1)];
}
至:
/*-------------------------------------vvv--*/
char *random_str = malloc(RAND_STR_LEN + 1);
for (int i = 0; i < RAND_STR_LEN; i++) {
random_str[i] = alpha_num_str[rand() % (strlen(alpha_num_str) - 1)];
}
random_str[RAND_STR_LEN] = '\0'; /* add zero termination */
筆記:
如果你想 select 來自alpha_num_str
中所有可用字符的隨機字符,你應該使用: rand() % (strlen(alpha_num_str))
(沒有-1
)。 這是因為x % n
將返回0..n-1
的值。
同樣出於效率原因,您可以在循環之前計算一次並將其存儲在變量中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.