C程序字符数组错误

时间:2017-06-22 16:58:25

标签: c arrays timer char

我试图了解char数组的大小" buf"正在影响我的间隔计时器设置。只要我将缓冲区分配给要组合的字符串的大小,一切都可以正常工作" Good"和" Day"。

当我设置" buf"的大小时对于更大的东西,在我的例子中,我的settimer函数失败了。

有没有人看到字符大小和settimer函数之间的联系?

如果我需要提供更多详细信息,请告知我,我会发布。

用arm-linux-gcc编译。没有编译错误。

失败

#define INTERVAL 30

void interval(void);

void exit_func (int i)
{
    signal(SIGINT,exit_func);
    printf("\nExiting!\n");
    exit(EXIT_FAILURE);
}
int main(){

    char buf[100] = "";
    char *cur = buf, * const end = buf + sizeof buf;

    cur += snprintf(cur, end-cur, "%s", "Good");
    if (cur < end) {
        cur += snprintf(cur, end-cur, "%s", "Day");
     }


     //timer code
     struct itimerval it_val;  /* for setting itimer */

    if (signal(SIGALRM, (void (*)(int)) interval) == SIG_ERR) {
        perror("Unable to catch SIGALRM");
        exit(1);
    }

    it_val.it_value.tv_sec =    INTERVAL; 
    it_val.it_interval = it_val.it_value;

    if (setitimer(ITIMER_REAL, &it_val, NULL) == -1) {
       perror("error calling setitimer()");
       exit(1);
    }

}

void interval(void) {
    //execute interval code
}

执行时失败,出现错误:调用setitimer()时出错:参数无效

作品

#define INTERVAL 30

void interval(void);

void exit_func (int i)
{
    signal(SIGINT,exit_func);
    printf("\nExiting!\n");
    exit(EXIT_FAILURE);
}

int main(){

    char buf[7] = "";
    char *cur = buf, * const end = buf + sizeof buf;

    cur += snprintf(cur, end-cur, "%s", "Good");
    if (cur < end) {
        cur += snprintf(cur, end-cur, "%s", "Day");
     }


     //timer code
     struct itimerval it_val;  /* for setting itimer */

    if (signal(SIGALRM, (void (*)(int)) interval) == SIG_ERR) {
        perror("Unable to catch SIGALRM");
        exit(1);
    }

    it_val.it_value.tv_sec =    INTERVAL; 
    it_val.it_interval = it_val.it_value;

    if (setitimer(ITIMER_REAL, &it_val, NULL) == -1) {
       perror("error calling setitimer()");
       exit(1);
    }

}

void interval(void) {
    //execute interval code
}

0 个答案:

没有答案