2013-06-02 48 views
-1

我有下面的代碼,並且當我在第20行(靠近底部)沒有int milli =運行它時,它運行得很好,但是當我將函數的結果分配給變量( milli)它引發了分段錯誤。我看不出造成段錯誤的區別。整數分配C分段錯誤

#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); 
} 
+0

你的問題是,timeval_struct從未分配。你需要像'rawtime'那樣做,這樣它就可以在堆棧中,或者手動爲'malloc'存儲器並且在最後「免費」。 – Dave

+1

這很愚蠢。你的'timeval_struct'指針沒有被初始化。 –

+1

在爲其分配一個值之前,您不能使用變量的值。 –

回答

1

您已將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); 
} 
+0

感謝您的回答,當我看到我實施此解決方案的意見,它的工作,併爲此,你可以得到正確的答案。 –

2

代碼崩潰,因爲timeval_struct指針未初始化。您需要分配一個struct timeval它,或使用自動變量而不是一個指針,就像這樣:

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

Demo on ideone

3

timeval_struct指向哪裏?你沒有爲此分配空間。 可以使用malloc或聲明struct timeval timeval_struct;並將其地址傳遞給gettimeofday(&timeval_struct, NULL)

+0

感謝您的回答,它的工作,但我跟着亞當斯的答案,因爲它更全面。我仍然投票支持你的。謝謝。 –

+0

沒有難過的感覺,我upvoted你的問題,以及:-) – Jens