如何在C中正确释放分配的内存?

时间:2016-09-19 18:43:55

标签: c malloc free

我有两个功能。在free我在main函数中分配了我想要char* find_host(char* filename){ char *x = malloc(20); sprintf(x, filename); const char* t = "10"; int len = (int) strcspn(filename, t); x[len] = '\0'; 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

如何正确npm install pg-promise --save记忆?

1 个答案:

答案 0 :(得分:3)

您只能通过调用free()及其兄弟实际返回的指针值调用malloc()。由于您希望跳过初始字符,因此可以在填充缓冲区时跳过,而不是返回更改的指针。

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] = '\0';
    return x;
}