簡體   English   中英

整數賦值的C分段錯誤

[英]C segmentation fault with integer assignment

我有下面的代碼,當我在第20行(在底部附近)沒有int milli =情況下運行它時,它運行得很好,但是,當我將函數的結果分配給變量( milli )時,它將引發分段錯誤。 我看不出導致段錯誤的區別。

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

// convert a timeval and time to milliseconds of today
int seconds_of_day(struct timeval *sec, struct tm *tim){
    long int milli_since_epoch = (sec->tv_sec * 1000)+(sec->tv_usec/100);
    return 0; // this is return 0 only for debugging
}

int main(){
    struct timeval *timeval_struct;
    time_t rawtime;
    struct tm *tm_struct;

    gettimeofday(timeval_struct, NULL);
    time(&rawtime);
    tm_struct = gmtime(&rawtime);

    int milli = seconds_of_day(timeval_struct, tm_struct);

    return(0);
}

timeval_struct指向哪里? 您沒有為此分配空間。 使用malloc或聲明一個struct timeval timeval_struct; 並將其地址傳遞給gettimeofday(&timeval_struct, NULL)

代碼崩潰,因為timeval_struct指針未初始化。 您需要為其分配一個struct timeval ,或使用自動變量而不是指針,如下所示:

struct timeval timeval_struct;
...
gettimeofday(&timeval_struct, NULL);
...
int milli = seconds_of_day(&timeval_struct, tm_struct);

ideone演示

您已將timeval_struct聲明為指針,但是尚未為其分配內存。 因此,它指向您的程序不擁有的未定義內存。 seconds_of_day()嘗試訪問timeval結構時,它會崩潰。

您可以通過將timeval_struct聲明為實際的結構而不是指針來解決此問題:

int main() {
    struct timeval timeval_struct;  // Actual struct, not pointer.
    time_t rawtime;
    struct tm *tm_struct;

    gettimeofday(&timeval_struct, NULL);  // Pass address of struct.
    time(&rawtime);
    // This is OK: gmtime() returns a pointer to allocated memory.
    tm_struct = gmtime(&rawtime);

    // Pass address of allocated timeval_struct.
    // NOTE:  seconds_of_day() does not use tm_struct at all.
    int milli = seconds_of_day(&timeval_struct, tm_struct);

    return(0);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM