c - gettimeofday() 上的奇怪标记

标签 c gettimeofday

我为我所在大学的抽样作业编写了这段代码。

#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char **argv){
    struct timeval tv;

    float t = atoi(argv[1]);  //sampling time period in sec's
    float dt = atoi(argv[2]);   //sampling rate in msec's
    double time;
    int nsamples = t/dt * 1000; //number of samples floored

    //samples storage array
    double *samples;
    samples = malloc(nsamples);

    printf("%d\n\n",nsamples);

    int c = 0;  //array index
    double divergance;

    gettimeofday(&tv, NULL);
    time =(double) tv.tv_sec + tv.tv_usec / 1000000.0f;
    samples[c] = time;
    printf("time: %f\n", samples[c]);

    usleep(dt * 1000);

    while(c<nsamples){
      c++;

      gettimeofday(&tv, NULL);
      time = (double) tv.tv_sec + tv.tv_usec / 1000000.0f;
      samples[c] = time;

      //divergance calculated in msec's
      divergance = (samples[c] - samples[c-1]);
      if (c==9){
        printf("%f \n \n%f", samples[c-1], samples[c]);
      }
      printf("time: %f\ndivergance: %f ms\n\n", samples[c], divergance*1000);

      usleep(dt *1000);
    }

}

这是我的输出

time: 1557335682.435666 divergance: 200.127125 ms

time: 1557335682.635813 divergance: 200.146914 ms

time: 1557335682.835952 divergance: 200.139046 ms

time: 1557335683.036075 divergance: 200.123072 ms

time: 1557335683.236192 divergance: -50328976507548121002151598324465532616014103321089770750300716493231241208217866953937760599346823570331739493744117764925654540012842402655523878795775819489233146901362588461216017208320541658368563434403808909221817741213696.000000 ms

time: 1557335683.436400 divergance: 1557335683436.399902 ms

time: 1557335683.636521 divergance: 1557335683636.520752 ms

time: 1557335683.836647 divergance: 1557335683836.646973 ms

有谁知道第五次计算的奇怪输出是什么?我无法想象任何合乎逻辑的解释,因为我以前没有遇到过任何类似的“错误”。它是否与 gettimeofday() 函数的某些特定功能有关?

注意:输入是 10200

最佳答案

您没有为样本分配足够的空间:

samples = malloc(nsamples);

malloc 函数为指定数量的字节 分配空间,而不是数组元素的数量。所以你的数组比你想象的要短得多。这意味着你最终会写到数组的末尾,调用 undefined behavior .

您需要将元素数量乘以元素大小才能分配正确的空间量:

samples = malloc(nsamples * sizeof(*samples));

你在访问数组时也有一个差一个错误:

int c = 0;
...
while(c<nsamples){
  c++;
  ...
  samples[c] = time;
  ...
}

这也会写到数组末尾,特别是一个数组元素太多了。

将循环更改为从值 1 开始并在结束时递增。

int c = 0;
...
c = 1;
while(c<nsamples){
  ...
  samples[c] = time;
  ...
  c++;
}

关于c - gettimeofday() 上的奇怪标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56046095/

相关文章:

c - 随机函数中的枚举

c - pthreads,我如何使用不同的类型?

c - gettimeofday 的时间未按应有的方式更新

c - gettimeofday - 解释确切的 struct timeval 字段的含义

php - PHP uniqid()源码相关问题

c - gcc 优化对共享库操作的影响

c - 为作为结构一部分的字符指针分配内存

C 在数组中分配错误的索引

c - 将指向结构的指针传递给c中的函数时出错

null - Swift:gettimeofday 和不安全指针