問題是這裏:
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