malloc + strdup是否会泄漏内存?

Mat*_*toe 2 c memory malloc memory-management strdup

附:

char *x = malloc(1024);
strcpy(x, "asdf");
x = strdup(x);
free(x); // OK
free(x); // Segfault
Run Code Online (Sandbox Code Playgroud)

如果我只是释放一次,我还会泄漏吗?如果是这样,如何避免呢?

Ker*_* SB 5

泄漏内存是因为忘记了第一个指针.像这样做:

char * x = malloc(1024);
strcpy(x, "asdf");
char * y = strdup(x);

free(x); 
free(y);
Run Code Online (Sandbox Code Playgroud)