调用GetSystemTime()函数时出现分段故障(Windows)

Segmentation Fault upon call to GetSystemTime() function (Windows)

本文关键字:分段 故障 Windows GetSystemTime 函数 调用      更新时间:2023-10-16

我在处理分段故障时遇到问题。以下健全性检查抛出一个:

#include <windows.h>
int main()
{
    LPSYSTEMTIME startTime;
    GetSystemTime(startTime);
}

然而,我在一个更大的程序中使用了相同的代码,它运行起来没有问题。我曾尝试在不同的地方添加延迟,以防问题源于GetSystemTime()中的某种多线程,但它并没有解决问题。

我正在CodeBlocks中使用MinGW GCC进行编译。

LPSYSTEMTIME是指向SYSTEMTIME结构的指针。你没有初始化指针,所以它指向风景中的某个地方,因此出现了访问违规/seg错误。

为了使代码正常工作,您必须确保指针指向有效的SYSTEMTIME结构。根据MSDN文档,Microsoft明确警告您,为指针传递NULL将导致访问冲突。

您使用的是未初始化的指针。这样效果更好:

#include <windows.h>
int main()
{
    SYSTEMTIME startTime;
    GetSystemTime(&startTime);
}

LPSYSTEMTIME是一个指针,您需要分配内存,或者需要释放LPSYSTEMTIME中的LP并调用函数,如:

SYSTEMTIME startTime;
GetSystemTime(&startTime);

LPSYSTEMTIME是指向SYSTEMTIME的指针,但尚未初始化。

试试这个:

SYSTEMTIME startTime = { 0 };
GetSystemTime(&startTime);

对于使用LPSYSTEMTIME,您应该编写以下内容:

SYSTEMTIME  systemTime; //allocation of memory
printf("%pn", &systemTime.wDay); // we can see address of wDay for example.
LPSYSTEMTIME st = &systemTime;
GetSystemTime(st);
printf("%d n", st->wDay);  //display result 
printf("%d n", (*st).wDay); //display the same result