gpt4 book ai didi

c - 如何正确发送 time_t 指针到函数?尝试这样做时遇到 valgrind 错误

转载 作者:行者123 更新时间:2023-11-30 21:09:09 26 4
gpt4 key购买 nike

我正在尝试使用 time_t 指针变量将 time_t 发送到函数。编译代码时我没有收到任何编译器警告,但使用 valgrind 运行代码时出现 valgrind 错误。

我的代码:

printTime(time_t *time){
<prints time>
}
int main(void){
struct tm beginTime = {0};
time_t *begin = 0;

strptime("2012",""%Y,&beginTime);
beginTime.tm_isdst = -1;
*begin = mktime(&beginTime); **<-- Valgrind error points here**

printTime(begin);


return 0;
}

这是我收到的 valgrind 错误:

Invalid write of size 8. (Points at the location pointed at above)

最佳答案

发布的代码中有几个语法错误。

编译时,启用所有警告,然后修复这些警告

以下代码:

  1. 干净地编译
  2. 运行不会崩溃

现在的代码:

#include <stdio.h>
#include <time.h>



void printTime(time_t *time)
{
(void)time;
//<prints time>
}


int main(void)
{
struct tm beginTime = {0};
time_t *begin = 0;

strptime("2012","%Y",&beginTime);
beginTime.tm_isdst = -1;
begin = mktime(&beginTime); // << notice no '*' before 'begin'
// because 'begin' is already declared as a pointer

printTime(begin);


return 0;
}

如果 valgrind 继续指示问题,您可以尝试将 begin 传递给 free()

即在 return 0; 语句之前插入:

free( begin );

关于c - 如何正确发送 time_t 指针到函数?尝试这样做时遇到 valgrind 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35517960/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com