c - CFDataCreateWithBytesNoCopy() wont work with "const char var[xx]" but will with malloc? -
just looking explanation of following, if variable digest isn't allocated manually info returned cfdatacreatewithbytesnocopy() continuously changes when referenced throughout program.
cfdataref sha1(cfstringref string) { unsigned char* digest = malloc(cc_sha1_digest_length); const char* cdata = cfstringgetcstringptr(string, cfstringgetfastestencoding(string)); cc_sha1(cdata, strlen(cdata), digest); cfdataref sha = cfdatacreatewithbytesnocopy(kcfallocatordefault, digest, cc_sha1_digest_length, kcfallocatordefault); free(digest); cfrelease(string); homecoming sha; }
where wont work...
cfdataref sha1(cfstringref string) { unsigned char digest[cc_sha1_digest_length]; const char* cdata = cfstringgetcstringptr(string, cfstringgetfastestencoding(string)); cc_sha1(cdata, strlen(cdata), digest); cfdataref sha = cfdatacreatewithbytesnocopy(kcfallocatordefault, digest, cc_sha1_digest_length, kcfallocatordefault); homecoming sha; }
also there memory leaks in top code?
second parameter of cfdatacreatewithbytesnocopy "pointer byte buffer used backing store of cfdata object" , in give-and-take section, find "the created object not re-create external buffer internal storage instead uses buffer backing store".
now in code unsigned char digest[cc_sha1_digest_length];
array automatic storage duration, means deallocated 1 time execution leaves scope defined.
note documentation states the external buffer deallocated when cfdata object deallocated.
c pointers malloc core-foundation
No comments:
Post a Comment