我应该释放由setlocale返回的指针吗?

int main(int argc, char *argv[]) { char *ret = setlocale(LC_ALL, NULL); // should I free 'ret' ??? // free(ret); return 0; } 

我已经在Linux和OS X 10.10上都试过了,在Linux中,我不能调用'free',但是在OS X中,如果我不叫'free',valgrind会抱怨内存泄漏。

 ==62032== Memcheck, a memory error detector ==62032== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al. ==62032== Using Valgrind-3.11.0.SVN and LibVEX; rerun with -h for copyright info ==62032== Command: ./a.out ==62032== --62032-- ./a.out: --62032-- dSYM directory is missing; consider using --dsymutil=yes ==62032== ==62032== HEAP SUMMARY: ==62032== in use at exit: 129,789 bytes in 436 blocks ==62032== total heap usage: 519 allocs, 83 frees, 147,421 bytes allocated ==62032== ==62032== 231 bytes in 1 blocks are definitely lost in loss record 63 of 91 ==62032== at 0x10000859B: malloc (in /usr/local/Cellar/valgrind/HEAD/lib/valgrind/vgpreload_memcheck-amd64-darwin.so) ==62032== by 0x1001E68C8: currentlocale (in /usr/lib/system/libsystem_c.dylib) ==62032== by 0x100000F6B: main (in ./a.out) ==62032== ==62032== LEAK SUMMARY: ==62032== definitely lost: 231 bytes in 1 blocks ==62032== indirectly lost: 0 bytes in 0 blocks ==62032== possibly lost: 0 bytes in 0 blocks ==62032== still reachable: 94,869 bytes in 10 blocks ==62032== suppressed: 34,689 bytes in 425 blocks ==62032== Reachable blocks (those to which a pointer was found) are not shown. ==62032== To see them, rerun with: --leak-check=full --show-leak-kinds=all ==62032== ==62032== For counts of detected and suppressed errors, rerun with: -v ==62032== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 17 from 17) 

所以,在Linux中,如果我叫'免费',它会崩溃。 在OS X中,如果我不叫“空闲”,它有内存泄漏。

你不应该free你得到的字符串。 根据C11标准:

7.11.1.1 setlocale函数

setlocale函数返回的指向字符串的指针是这样的,使用该字符串值及其相关类别的后续调用将恢复程序语言环境的该部分。 指向的字符串不能被程序修改,但可能会被随后调用setlocale函数覆盖

另外,Linux 手册页说:

这个字符串可能被分配在静态存储器中。

这会导致你的程序崩溃,如果你试图free它。

看起来Linux实现使用静态存储,但OSX使用malloc 。 不管发生了什么,你都不应该修改它,因为标准不允许你这样做 – 在OSX上它是安全的是一个你应该忽略的实现怪癖。 Valgrind在这里基本上给你一个误判。