Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

Commit ac329e6

Browse files
committed
Avoid memory allocation in EnumSymbols for small buffers
1 parent 2913cdc commit ac329e6

File tree

1 file changed

+20
-15
lines changed

1 file changed

+20
-15
lines changed

src/corefx/System.Globalization.Native/pal_calendarData.c

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -319,39 +319,44 @@ bool EnumSymbols(const char* locale,
319319
udat_setCalendar(pFormat, pCalendar);
320320

321321
int32_t symbolCount = udat_countSymbols(pFormat, type);
322+
UChar stackSymbolBuf[100];
323+
UChar* symbolBuf;
322324

323-
for (int32_t i = startIndex; i < symbolCount; i++)
325+
for (int32_t i = startIndex; U_SUCCESS(err) && i < symbolCount; i++)
324326
{
325327
UErrorCode ignore = U_ZERO_ERROR;
326328
int symbolLen = udat_getSymbols(pFormat, type, i, NULL, 0, &ignore) + 1;
327329

328-
UChar* symbolBuf = calloc(symbolLen, sizeof(UChar));
329-
if (symbolBuf == NULL)
330+
if (symbolLen <= sizeof(stackSymbolBuf) / sizeof(stackSymbolBuf[0]))
330331
{
331-
udat_close(pFormat);
332-
ucal_close(pCalendar);
333-
return false;
332+
symbolBuf = stackSymbolBuf;
333+
}
334+
else
335+
{
336+
symbolBuf = calloc(symbolLen, sizeof(UChar));
337+
if (symbolBuf == NULL)
338+
{
339+
err = U_MEMORY_ALLOCATION_ERROR;
340+
break;
341+
}
334342
}
335343

336344
udat_getSymbols(pFormat, type, i, symbolBuf, symbolLen, &err);
337345

338-
assert(U_SUCCESS(err));
346+
if (U_SUCCESS(err))
347+
{
348+
callback(symbolBuf, context);
349+
}
339350

340-
if (U_FAILURE(err))
351+
if (symbolBuf != stackSymbolBuf)
341352
{
342-
udat_close(pFormat);
343-
ucal_close(pCalendar);
344353
free(symbolBuf);
345-
return false;
346354
}
347-
348-
callback(symbolBuf, context);
349-
free(symbolBuf);
350355
}
351356

352357
udat_close(pFormat);
353358
ucal_close(pCalendar);
354-
return true;
359+
return U_SUCCESS(err);
355360
}
356361

357362
bool EnumUResourceBundle(const UResourceBundle* bundle, EnumCalendarInfoCallback callback, const void* context)

0 commit comments

Comments
 (0)