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

noi*_*put 7 c linux macos valgrind setlocale

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

我已经在Linux和OS X 10.10上尝试过,在Linux上,我不能称之为'免费',但在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)
Run Code Online (Sandbox Code Playgroud)

所以,在Linux中,如果我称之为"免费",它就会崩溃.在OS X中,如果我不调用'free',它会有内存泄漏.

Pat*_*ins 10

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

7.11.1.1 setlocale功能

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

此外,Linux 手册页说:

该字符串可以在静态存储中分配.

如果您尝试过这会导致程序崩溃free.

看起来Linux实现使用静态存储,但OSX使用静态存储malloc.无论发生什么事情,你都不应该修改它,因为标准不允许你这样做 - 事实上它在OSX上是安全的是你应该忽略的实现怪癖.Valgrind在这里给你一个误报.