如何正确释放 C 中分配的内存?
How to properly free an allocated memory in C?
我有两个功能。在 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] = '[=10=]';
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()
及其兄弟的调用实际 return 对指针值调用 free()
。由于您希望跳过初始字符,因此可以在填充缓冲区时进行跳过,而不是 return 更改后的指针。
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] = '[=10=]';
return x;
}
我有两个功能。在 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] = '[=10=]';
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()
及其兄弟的调用实际 return 对指针值调用 free()
。由于您希望跳过初始字符,因此可以在填充缓冲区时进行跳过,而不是 return 更改后的指针。
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] = '[=10=]';
return x;
}