Skip to content

Instantly share code, notes, and snippets.

@tknopp tknopp/strtod.c
Created Feb 28, 2014

Embed
What would you like to do?
Locale independent strtod
#if defined(_OS_WINDOWS_)
#include <stdlib.h>
#include <locale.h>
// Cache locale object
static int c_locale_initialized = 0;
static _locale_t c_locale;
_locale_t get_c_locale()
{
if(!c_locale_initialized)
{
c_locale_initialized = 1;
c_locale = _create_locale(LC_ALL,"C");
}
return c_locale;
}
double strtod_c(const char *nptr, char **endptr)
{
return _strtod_l(nptr, endptr, get_c_locale());
}
#else
#include <stdlib.h>
#include <xlocale.h>
// Cache locale object
static int c_locale_initialized = 0;
static locale_t c_locale;
locale_t get_c_locale()
{
if(!c_locale_initialized)
{
c_locale_initialized = 1;
c_locale = newlocale(LC_ALL_MASK, NULL, NULL);
}
return c_locale;
}
double strtod_c(const char *nptr, char **endptr)
{
return strtod_l(nptr, endptr, get_c_locale());
}
#endif
@pavel-perina

This comment has been minimized.

Copy link

pavel-perina commented Jul 31, 2017

Please change

   c_locale = newlocale(LC_ALL_MASK, NULL, NULL);

with

   c_locale = newlocale(LC_ALL_MASK, "C", NULL);

on line 39. Otherwise c_locale will be set to 0 and passing 0 to strtod_l will cause crash (at least in my glibc implementation).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.