Should I free the pointer returned by setlocale?

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

I tried both on Linux and OS X 10.10, on Linux I should not call it "free", but on OS X, if I do not call it "free", valgrind complains about a memory leak.

 ==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) 

So, on Linux, if I call "free," it will work. in OS X, if I don't call "free", it has a memory leak.

+6
source share
1 answer

You must not free line you receive. In accordance with standard C11:

7.11.1.1 setlocale function

The pointer to the string returned by the setlocale function is such that a subsequent call with this string value and the category associated with it will restore this part of the locale program. The specified line should not be changed by the program , but can be overwritten by a subsequent call to setlocale Function

In addition, Linux man pages say:

This line can be allocated to static storage.

which will crash your program if you try free it.

It looks like the Linux implementation uses static storage, but OSX uses malloc . No matter what happens under the hood, you should not change it , because the standard forbids you to do this. The fact that this is safe for OSX is an implementation error that you should ignore. Valgrind essentially gives you a false result.

+8
source

Source: https://habr.com/ru/post/983953/


All Articles