Skip to content

Commit b35abe7

Browse files
author
Зишан Мирза
committed
use stack allocation of memory instead of heap allocation
1 parent cb9027f commit b35abe7

File tree

4 files changed

+9
-9
lines changed

4 files changed

+9
-9
lines changed

libc/src/time/time_utils.cpp

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
#include "src/time/timezone.h"
1515
#include <stdio.h>
1616
#include <stdlib.h>
17+
#include <string.h>
1718

1819
namespace LIBC_NAMESPACE_DECL {
1920
namespace time_utils {
@@ -154,12 +155,13 @@ int64_t update_from_seconds(int64_t total_seconds, struct tm *tm) {
154155
if (years > INT_MAX || years < INT_MIN)
155156
return time_utils::out_of_range();
156157

157-
char *timezone = (char *)malloc(sizeof(char) * TimeConstants::TIMEZONE_SIZE);
158-
timezone = getenv("TZ");
158+
char timezone[TimeConstants::TIMEZONE_SIZE];
159+
char *env_tz = getenv("TZ");
159160
FILE *fp = NULL;
160-
if (timezone == NULL) {
161-
timezone =
162-
(char *)realloc(timezone, sizeof(char) * TimeConstants::TIMEZONE_SIZE);
161+
if (env_tz) {
162+
strncpy(timezone, env_tz, sizeof(timezone));
163+
timezone[sizeof(timezone) - 1] = '\0';
164+
} else {
163165
fp = fopen("/etc/timezone", "rb");
164166
if (fp == NULL) {
165167
return time_utils::out_of_range();

libc/src/time/timezone.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ int get_timezone_offset(char *timezone) {
3232
offset = -8;
3333
}
3434

35-
if (tz.starts_with("America/New_York")) {
35+
if (tz.ends_with("New_York")) {
3636
offset = -5;
3737
}
3838
}

libc/src/time/timezone.h

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,6 @@
2323
namespace LIBC_NAMESPACE_DECL {
2424
namespace timezone {
2525

26-
#define TZ_HEADER "TZif"
27-
2826
extern int get_timezone_offset(char *timezone);
2927

3028
} // namespace timezone

libc/test/src/time/localtime_test.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ TEST(LlvmLibcLocaltime, ValidUnixTimestampTzEnvironmentVariableEuropeBerlin) {
154154
ASSERT_EQ(1, result->tm_isdst);
155155
}
156156

157-
TEST(LlvmLibcLocaltime, ValidUnixTimestampTzEnvironmentVariableRussiaMoscow) {
157+
TEST(LlvmLibcLocaltime, ValidUnixTimestampTzEnvironmentVariableEuropeMoscow) {
158158
set_env_var("TZ=Europe/Moscow");
159159

160160
time_t t_ptr = 1627225465;

0 commit comments

Comments
 (0)