结构体String内存扩容异常排查:内存分配与拷贝问题咨询
Let’s walk through the most common pitfalls that could be causing your capacity doubling logic to fail silently (no compiler errors but unexpected behavior):
You’re modifying a copy of the struct pointer, not the original
If your function takes aString *strparameter and tries to reassignstrto a new struct (likestr = new_struct_ptr;), you’re only changing the pointer’s local copy inside the function. The original pointer in your main code never gets updated. To fix this, you need to pass a pointer-to-pointer (String **str) so you can modify the original pointer, or modify the members of the existing struct instead of replacing the whole struct.Skipping memory allocation failure checks
malloc/realloccan returnNULLif there’s not enough memory. If you don’t check for this, your code will proceed with an invalid pointer, leading to undefined behavior that might look like "capacity didn’t update". Always validate allocation results:String *new_str = malloc(sizeof(String)); if (!new_str) { /* handle error (e.g., return false/error code) */ } new_str->ptr = malloc(new_str->capa); if (!new_str->ptr) { free(new_str); /* handle error */ }Incorrect data copying logic
Double-check that you’re copying exactlystr->lenbytes of data (plus a null terminator if yourptris a C-style string). If you accidentally usestr->capainstead ofstr->len, you might copy uninitialized garbage, or if you copy fewer bytes, your data gets truncated. This can make it seem like the capacity change didn’t work even if it did.Forgetting to free old memory (and leaking resources)
If you create a new struct and newptr, you need to free the old struct’sptrand the old struct itself (if it was dynamically allocated). Not doing this leads to memory leaks, and if you don’t update the original pointer to point to the new struct, your code will still use the old, smaller-capacity struct.Handling zero initial capacity wrong
If your original struct hascapa = 0, doubling it gives you0again—so you’ll never allocate any meaningful memory. Add a check to set a default initial capacity (like 16) whencapais zero:int new_capa = (old_str->capa == 0) ? 16 : old_str->capa * 2;Confusing struct replacement with member modification
If your originalStringis allocated on the stack (not withmalloc), you can’t replace the entire struct with a heap-allocated one—this will break stack memory integrity. Instead, reallocate theptrmember in place and update thecapavalue directly in the existing stack struct.
Example of a Working Implementation (Pointer-to-Pointer Version)
#include <stdlib.h> #include <string.h> typedef struct { char* ptr; int len; int capa; } String; bool double_string_capacity(String **str_ptr) { if (!str_ptr || !*str_ptr) return false; String *old_str = *str_ptr; int new_capa = (old_str->capa == 0) ? 16 : old_str->capa * 2; // Allocate new struct and buffer String *new_str = malloc(sizeof(String)); char *new_ptr = malloc(new_capa); if (!new_str || !new_ptr) { free(new_str); free(new_ptr); return false; } // Copy existing data memcpy(new_ptr, old_str->ptr, old_str->len); // Uncomment if using null-terminated strings: // new_ptr[old_str->len] = '\0'; // Clean up old memory free(old_str->ptr); free(old_str); // Update new struct members and original pointer new_str->ptr = new_ptr; new_str->len = old_str->len; new_str->capa = new_capa; *str_ptr = new_str; return true; }
内容的提问来源于stack exchange,提问作者user9659728

