[英]C using malloc and realloc to dynamically increase string length
目前正在學習 C 中的內存管理,我目前遇到了在循環迭代時增加字符串長度的問題。
我試圖找出邏輯上的方法是這樣的:
// return string with "X" removed
char * notX(char * string){
result = "";
if(for int = 0; i < strlen(string); i++){
if (string[i] != 'X') {
result += string[i];
}
}
return result;
}
在其他語言中很簡單,但在 C 中管理內存使其有點挑戰性。 我遇到的困難是當我使用 malloc 和 realloc 來初始化和更改我的字符串的大小時。 在我目前嘗試的代碼中:
char * notX(char * string){
char* res = malloc(sizeof(char*)); // allocate memory for string of size 1;
res = ""; // attempted to initialize the string. Fairly certain this is incorrect
char tmp[2]; // temporary string to hold value to be concatenated
if(for int = 0; i < strlen(string); i++){
if (string[i] != 'X') {
res = realloc(res, sizeof(res) + sizeof(char*)); // reallocate res and increasing its size by 1 character
tmp[0] = string[i];
tmp[1] = '\0';
strcat(res, tmp);
}
}
return result;
}
請注意,我發現成功將結果初始化為一些大數組,例如:
char res[100];
但是,我想了解如何在不初始化具有固定大小的數組的情況下解決此問題,因為這可能會浪費內存空間或內存不足。
realloc
需要分配的字節數。 size
為添加到res
每個字符遞增。 size + 2
用於提供正在添加的當前字符和終止零。
檢查realloc
的返回。 NULL 表示失敗。 如果realloc
失敗,使用tmp
允許返回res
。
char * notX(char * string){
char* res = NULL;//so realloc will work on first call
char* tmp = NULL;//temp pointer during realloc
size_t size = 0;
size_t index = 0;
while ( string[index]) {//not the terminating zero
if ( string[index] != 'X') {
if ( NULL == ( tmp = realloc(res, size + 2))) {//+ 2 for character and zero
fprintf ( stderr, "realloc problem\n");
if ( res) {//not NULL
res[size] = 0;//terminate
}
return res;
}
res = tmp;//assign realloc pointer back to res
res[size] = string[index];
++size;
}
++index;//next character
}
if ( res) {//not NULL
res[size] = 0;//terminate
}
return res;
}
此代碼中的 2 個主要錯誤:
malloc和realloc函數帶有調用sizeof(char*)
。 在這種情況下的sizeof(字符*)的結果是一個指針的大小,而不是一個char的,所以你要替換char*
與char
的功能的sizeof。
res = "";
是不正確的。 您主要有內存泄漏,因為您丟失了指向 malloc 函數中剛剛分配的內存的指針,次要但同樣重要的是,當調用 realloc 函數超過 res 初始化為空字符串(或更好的常量字符串)時,您有未定義的行為,在上述初始化之后,內存不再是動態管理的。 為了替代這個初始化,我認為將 memset 設置為 0 是最好的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.