如前所述,您的代码将不起作用。
strcpy(target, tmp)
在这两个函数中使用时都会出现错误。您需要了解,这样做几乎肯定会溢出target
. 如果目标只是指向一个数组strlen(target + 1)
(目标中的所有字符加上一个尾随的 NULL),那么您正在复制一个tmp
太短的内存数组的内容char
。为了说明这一点,运行一个循环,例如:
/* allocate two strings, containing copies
of constant string "Hello World" */
local_string = strdup("Hello World");
expression = strdup("Hello World");
for (i = 0; i < 100; i++) {
edit_char();
edit_char2(local_string);
printf("global_string after: [%s]\n", expression);
printf("local_string after: [%s]\n", local_string);
}
几乎总是会导致程序异常终止,早在第 100 次迭代之前。在 Debian Linux Squeeze 上,我得到以下输出:
user@host$ ./a.out
global_string before: [Hello World]
local_string before: [Hello World]
global_string after: [*Hello World]
[...]
global_string after: [************Hello World]
local_string after: [////////////Hello World]
*** glibc detected *** ./a.out: double free or corruption (!prev): 0x00000000020e2050
你需要使用更多的指针魔法来实现你想要的。这是一个工作示例,设计改进限制了代码重复:
输出
user@host$ ./a.out
global_string before: [Hello World]
local_string before: [Hello World]
global_string after: [*Hello World]
local_string after: [/Hello World]
代码
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char *global_string;
void add_one_leading_character(char leading, char **pointer_to_string)
{
char *new_string;
char *old_string;
/* old_string will hold the content of
pointer_to_string, for convenience */
old_string = *pointer_to_string;
/* allocate a new, empty string
(= filled with NULLs) holding enough space
for an additional character */
new_string = calloc(sizeof(*old_string), strlen(old_string) + 2);
/* new_string now holds the leading character,
followed by NULLs */
new_string[0] = leading;
/* concatenate the old_string to the new_string */
strcat(new_string, old_string);
/* make the pointer parameter points to the
address of new_string */
*pointer_to_string = new_string;
/* free the memory pointed by old_string */
free(old_string);
}
int main(int ac, char **av)
{
char *local_string;
/* allocate two strings, containing copies
of constant string "Hello World" */
local_string = strdup("Hello World");
global_string = strdup("Hello World");
printf("global_string before: [%s]\n", global_string);
printf("local_string before: [%s]\n", local_string);
/* add leading characters */
add_one_leading_character('/', &local_string);
add_one_leading_character('*', &global_string);
printf("global_string after: [%s]\n", global_string);
printf("local_string after: [%s]\n", local_string);
}