我不明白,爲什麼在這段代碼,調用「自由」導致段錯誤:malloc的,免費的,分段錯誤
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *char_arr_allocator(int length);
int main(int argc, char* argv[0]){
char* stringa = NULL;
stringa = char_arr_allocator(100);
printf("stringa address: %p\n", stringa); // same address as "arr"
printf("stringa: %s\n",stringa);
//free(stringa);
return 0;
}
char *char_arr_allocator(int length) {
char *arr;
arr = malloc(length*sizeof(char));
arr = "xxxxxxx";
printf("arr address: %p\n", arr); // same address as "stringa"
return arr;
}
有人能解釋一下?
感謝, Segolas
也看看http://www.hpl.hp.com/personal/Hans_Boehm/gc/這太好了。 – 2010-10-08 12:21:27