Realloc设置指针为空
void test(){ char *c = malloc(strlen("I like coffe") + 1); strcpy(c, "I like coffe"); char **s = &c; while(strlen(*s) =p; i--){ w[i+1] = w[i]; } w[p] = c; }
此函数用于在char *
插入新字符。
此外,此function在while循环内。 它工作正常但是第三次循环运行时,它只设置*s = ""
。
我认为通过使用char *tmp
我可以保留数据,如果有任何错误的事情发生。 我不明白为什么P *s
被设置为空字符串。
您忘记在包含realloc()
的函数中将新值赋给*s
。
void test(void) // Unaltered; still broken! { char *c = malloc(strlen("I like coffe") + 1); strcpy(c, "I like coffe"); char **s = &c; while (strlen(*s) < 25) my_function(s); } void my_function(char **s) // Fixed one way { char *w = *s; size_t len = strlen(w) + 1; // Define and initialize len char *tmp = realloc(w, len + 2); if (tmp != NULL) w = tmp; *s = w; // Reassign to `*s` }
或者,更简单地说:
void my_function(char **s) // Fixed another way { char *w = *s; size_t len = strlen(w); // Define and initialize len char *tmp = realloc(w, len + 2); if (tmp != NULL) *s = tmp; // Reassign to `*s` }
分配给w
只设置局部变量,它是*s
的副本; 它不会重置调用代码中的指针。
请注意,即使使用此修复程序, test()
的循环也会运行很长时间,因为没有任何内容会改变c
字符串的长度。 还有另一个问题:你没有将s
的地址传递给my_function()
,所以my_function()
不能修改s
。
void test(void) { char *c = malloc(strlen("I like coffe") + 1); strcpy(c, "I like coffe"); while (strlen(c) < 25) { my_function(&c); strcat(c, "AZ"); // Grow string — not good in real code printf("%2zu: <<%s>>\n", strlen(c), c); } } void my_function(char **s) { char *w = *s; size_t len = strlen(w) + 1; // Define and initialize len char *tmp = realloc(w, len + 2); if (tmp != NULL) *s = tmp; // Reassign to `*s` }
这消除了指向test()
char的指针。 如果那是至关重要的,那么还有更多的想法要做。
代码尚未正式测试!
代码现已测试 - 你能说“猪的耳朵”吗? Copy'n'paste错误的材料使我的测试代码失败。 这是仪表化的工作版本 - valgrind
给它一个干净的健康状况。
#include #include #include static void my_function(char **s) { char *w = *s; size_t len = strlen(w) + 1; // Define and initialize len printf("M1: %p: %2zu: <<%s>>\n", (void *)w, len, w); char *tmp = realloc(w, len + 2); if (tmp != NULL) *s = tmp; // Reassign to `*s` printf("M2: %p: %2zu: <<%s>>\n", (void *)*s, strlen(*s), *s); } static void test(void) { char *c = malloc(strlen("I like coffe") + 1); if (c == 0) { fprintf(stderr, "Out of memory\n"); exit(EXIT_FAILURE); } strcpy(c, "I like coffe"); printf("T1: %p: %2zu: <<%s>>\n", (void *)c, strlen(c), c); while (strlen(c) < 25) { my_function(&c); printf("T2: %p: %2zu: <<%s>>\n", (void *)c, strlen(c), c); if (c == NULL) { fprintf(stderr, "Out of memory\n"); exit(EXIT_FAILURE); } strcat(c, "AZ"); // Grow string — not good in real code printf("T3: %p: %2zu: <<%s>>\n", (void *)c, strlen(c), c); } free(c); } int main(void) { test(); return 0; }