Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Library Function - freelocale()

C Library Function - freelocale()

C Standard Library - <locale.h> C Standard Library -

Description

freelocale() is a function in the C standard library used to free a locale object created by newlocale() . This function frees the resources associated with the locale object, preventing memory leaks.

Declaration

Below is the declaration of the freelocale() function.



#include 



void freelocale(locale_t locale);

Parameters

Return Value

Example

The following example demonstrates how to use freelocale() to free a locale object created by newlocale():

Example

#include

#include

#include // GNU extension

int

main

(

)

{

   

// Create a new locale object using the "en_US.UTF-8" locale setting

    locale_t newloc

=

newlocale

(

LC_ALL_MASK

,

"en_US.UTF-8"

,

(

locale_t

)

0

)

;

   

if

(

newloc

==

(

locale_t

)

0

)

{

       

perror

(

"newlocale"

)

;

       

return

1

;

   

}

   

// Set the current thread's locale object to the new one

    locale_t oldloc

=

uselocale

(

newloc

)

;

   

// Perform operations associated with the new locale object

   

struct

lconv

lc

=

localeconv

(

)

;

   

printf

(

"Decimal point character in new locale: %s\n"

,

lc

->

decimal_point

)

;

   

printf

(

"Thousands separator in new locale: %s\n"

,

lc

->

thousands_sep

)

;

   

// Restore the previous locale object

    uselocale

(

oldloc

)

;

   

// Free the new locale object

    freelocale

(

newloc

)

;

   

return

0

;

}

Let's compile and run the above program, which will produce the following result:



Decimal point character in new locale: .

Thousands separator in new locale: ,

Code Analysis

- Use `newlocale()` to create a new locale object, such as `locale_t newloc = newlocale(LC_ALL_MASK, "en_US.UTF-8", (locale_t)0);`. - Use `uselocale(newloc)` to switch the current thread's locale object to the newly created one and save the previous locale object, such as `locale_t oldloc = uselocale(newloc);`. - Perform operations associated with the new locale object, such as retrieving numeric and currency format information. - Use `uselocale(oldloc)` to restore the previous locale object, ensuring the program's locale settings return to their original state. - Use `freelocale(newloc)` to free the newly created locale object to prevent memory leaks.

Notes

Summary

freelocale() The function is used to free a locale object created by newlocale() . It helps manage and clean up resources associated with locale objects, preventing memory leaks. By properly using the newlocale(), uselocale() and freelocale() function, programmers can flexibly manage and switch a program's locale settings, enabling support for multiple languages and regions.

C Standard Library - <locale.h> C Standard Library -