我有两个函数。在find_host(...)
中,我为main
函数中的free
分配了内存。
char* find_host(char* filename){
char *x = malloc(20);
sprintf(x, filename);
const char* t = "10";
int len = (int) strcspn(filename, t);
x[len] = ' ';
return ++x;
}
int main(){
char *filename = "/CERN0/out_79.MERGE";
char *word = find_host(filename);
free(word);
return 0;
}
但free(word)
给了我:
*** Error in `/home/ken/.CLion2016.2/system/cmake/generated/First-6a656bbe/6a656bbe/Debug/First': free(): invalid pointer: 0x00000000008b1011 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x77725)[0x7f926862f725]
/lib/x86_64-linux-gnu/libc.so.6(+0x7ff4a)[0x7f9268637f4a]
/lib/x86_64-linux-gnu/libc.so.6(cfree+0x4c)[0x7f926863babc]
/home/ken/.CLion2016.2/system/cmake/generated/First-6a656bbe/6a656bbe/Debug/First[0x4006e9]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7f92685d8830]
/home/ken/.CLion2016.2/system/cmake/generated/First-6a656bbe/6a656bbe/Debug/First[0x400579]
======= Memory map: ========
如何正确使用free
内存?
只能在调用malloc()
及其同类函数实际返回的指针值上调用free()
。由于希望跳过初始字符,因此可以在填充缓冲区时跳过,而不是返回修改后的指针。
char* find_host(char* filename){
size_t sz = strlen(filename);
char *x = malloc(sz);
snprintf(x, sz, "%s", filename + 1);
const char* t = "10";
int len = (int) strcspn(filename, t);
x[len] = ' ';
return x;
}