Ani*_*dey 0 c memory-management realloc
void replace(char *str) {
unsigned int len = 0;
unsigned int no_of_spaces = 0;
while (*str) {
if ((char)*str == SPACE)
no_of_spaces++;
str++;
len++;
}
unsigned int new_len = len + 2 * no_of_spaces;
str = (char*) realloc(str, new_len * sizeof(char));
str[new_len] = '\0';
}
Run Code Online (Sandbox Code Playgroud)
我用的功能就像replace("random string");.
在这里,我试图增加字符串的大小,以便可以用另一个字符串替换空格.为此,我需要计算空格的数量,并获得原始字符串的长度.我已经能够做到这一点.
为了调整大小我正在使用realloc,但当我运行它,它给出了Aborted (core dumped)?
你的原始字符串是用malloc分配的吗?还是realloc?也许您正在尝试增加静态字符串的大小(字符串文字):
char sStatic[256]; // cannot realloc
char *sNonStatic = NULL; // can / must realloc
replace("random string") // cannot realloc within replace
Run Code Online (Sandbox Code Playgroud)
编辑:阅读完评论后,您应该获取传入字符串的副本,增加大小,然后输出一个副本/新字符串.您不能增加常量字符串的大小(字符串文字).
可以传递的唯一指针realloc是空指针和那些已经被退回calloc,malloc或realloc以前!
这很重要,因为你提到你调用了你的函数replace("random string")...是"random string"一个空指针,还是由其中一个*alloc函数返回的?不.也许您打算使用strdup或某事(例如char *foo = strdup("random string"); replace(foo); free(foo);)?strdup是一个POSIX函数(例如,不像函数那样的C标准*alloc),但它应该返回*alloc函数返回的内容.
遵循以下代码:
unsigned int new_len = len + 2 * no_of_spaces;
str = (char*) realloc(str, new_len * sizeof(char)); /* NOTE there's a potential memory leak
* when realloc returns NULL here, though
* that's the least of your problems */
Run Code Online (Sandbox Code Playgroud)
...你必须检查str以确保realloc成功,然后只有str0和之间的唯一有效索引new_len - 1.这是空指针取消引用或缓冲区溢出:
str[new_len] = '\0';
Run Code Online (Sandbox Code Playgroud)
也许你的意思是:
size_t new_len = len + 2 * no_of_spaces;
void *temp = realloc(str, new_len + 1); /* <--- NOTE +1 HERE! */
if (temp == NULL) {
/* XXX: Bomb out due to allocation failure */
}
str = temp;
Run Code Online (Sandbox Code Playgroud)
...现在有效索引介于0和之间new_len + 1 - 1,所以这是有效的:
str[new_len] = '\0';
Run Code Online (Sandbox Code Playgroud)