问题是这里:
void test(char **out){
char *f = (char *) malloc(10);
f = "123456";
*out = f;
return;
}
malloc的线分配在堆10个字节的内存。所以在这个阶段,f的地址将会在malloc碰巧抓住一块内存的地方。为了论证的目的,我们会说这是0x10000
然后,你分配f地址的文字字符串。
下面的代码打印出发生了什么。
#include <stdlib.h>
void test(char **out){
char *f = (char *) malloc(10);
printf("f after malloc = %p\n", f);
f = "123456";
printf("f after re-assignment = %p\n", f);
*out = f;
return;
}
int main(void){
char *A = NULL;
test(&A);
free(A);
return;
}
这里有一些替代方式中C.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
static char* b = "test 2";
void test2(char **out){
*out = b;
}
const char* test3(){
return "test 3";
}
void test4(char **out){
*out = (char *) malloc(10);
strcpy(*out, "test 4");
}
int main(void){
char *A = NULL;
char *B = NULL;
char *C = NULL;
/* Assign A to the address of a 'global' string */
test2(&A);
printf("A is now: %s\n", A);
/* Don't free this */
/* return a static string */
B = test3();
printf("B is now: %s\n", B);
/* allocate memory on heap and make a copy of data from a source to that memory location */
test4(&C);
printf("C is now: %s\n", C);
free(C); /* only C is allocated on heap so free this one */
}
与字符串工作'F = “123456”;'是内存泄漏。改为'strcpy(f,“123456”);' – BLUEPIXY 2014-10-11 18:30:34
你认为'f =“123456”;'这行是干什么的? – 2014-10-11 18:30:40
使用该strncpy来防止缓冲区溢出 – 2014-10-11 18:33:12