c - Does CFSTR() allocate memory? -
i understood cfstr() documentation indicate allocates memory. can return null on failure, , result available until program terminates regardless of whether 1 calls cfrelease() or drops reference. it's wrapping static string, surely has allocate cfstring class struct so. , such it's not appropriate use in long-running programs.
however, after pushback on this, tried following test program. don't see memory footprint in top increase. leaks reported valgrind don't vary loop size. there de-duplication happening?
#include <corefoundation/cfstring.h> #include <stdio.h> int main(void) { int count = 0; int chars = 0; (int = 0; < 100000000; i++) { cfstringref str = cfstr("goodbye."); if (str) { count++; chars += cfstringgetlength(str); // drop reference! } } printf("%d strings, %d chars\n", count, chars); cfstringref str = cfstr("hello, world."); cfshowstr(str); } another asker reported cfstr() does leak on windows. others it's objective c's @"string" literal syntax. cfstring reference mentions needing -fconstant-cfstrings on gcc 3.3. macro use magic compiler extension create these @ build time?
on macos x 10.8.5 machine, corefoundation/cfstring.h defines cfstr __builtin___cfstringmakeconstantstring except on windows or linux, uses non-builtin version.
so seems answer is, "it doesn't allocate on macos x or ios".
i don't know how verify they're in executable cfstringrefs, otool -tv says:
leaq 0x1c8(%rip), %rax ## objc cfstring ref: @"goodbye." instruction pointer relative addressing confirmation, , leaq means it's not calling allocate.
as discovered, on apple platforms, cfstr uses compiler built-in generate string @ compile time. embedded in executable fully-constructed, usable object; program doesn't perform allocation @ runtime cfstr. compiler merges duplicate string objects within single translation unit. i'm not sure if linker merges duplicates across object files.
on other platforms, apple doesn't control compiler, can't use compiler built-in embed constructed object in executable. instead, @ runtime, calls private library function __cfstringmakeconstantstring. can find source code of function in cfstring.c. keeps hash table maps argument (as c string) cfstring. “de-duplication”. doesn't remove entries table. each unique c string passed cfstr allocate memory persists until program exists. memory accessible call cfstr same string argument, calling “leak” questionable.
Comments
Post a Comment