2012-12-15 4 views
0

'time'함수와 'time.h'의 다른 함수를 사용하는 코드가 있는데 'time'은 매 시간마다 NULL을 반환합니다 (하하는 재미 있지만 'time'은 나에게 유용합니다. 그러한 방향으로주의를 기울이는 것)이 다시 실행됩니다. 어제 시작된 것만 큼 이상합니다. 비슷하지만 비슷한 기능의 이전 사용법은 (필자가 추가 한) 코드가 괜찮음을 입증했다.time.h에 정의 된 'time'함수가 NULL을 반환하는 이유는 무엇입니까?

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

#define EXIT_SUCCESS 0 
#define EXIT_FAILURE 1 

typedef struct tm tm; 

int logf(char input_string[]) 
{ 
    time_t* current_time_since_epoch; 
    time(current_time_since_epoch); 
    if (current_time_since_epoch == NULL) 
    { 
     printf("'time' returned NULL.\n"); 
     return EXIT_FAILURE; 
    } 
    tm* current_time_calandar_time = localtime(current_time_since_epoch); 
    if (current_time_calandar_time == NULL) 
    { 
     printf("'localtime' returned NULL.\n"); 
     return EXIT_FAILURE; 
    } 
    char current_time_textual_representation[20]; 
    strftime(current_time_textual_representation, 20, "%d-%m-%Y %H:%M:%S", current_time_calandar_time); 
    printf("%s\n", current_time_textual_representation); 
    printf("%s\n", input_string); 
    return EXIT_SUCCESS; 
} 

int main(void) 
{ 
    int check_logf = logf("Hello."); 
    if (check_logf == 0) exit(EXIT_SUCCESS); 
    else 
    { 
     printf("'logf' returned EXIT_FAILURE.\n"); 
     exit(EXIT_FAILURE); 
    } 
} 
+0

'stdlib.h'는'EXIT_SUCCESS'하고 (심지어 C89)에'EXIT_FAILURE' 정의 자체를 가지고, 그들은 휴대용입니다. 그러나,'EXIT_SUCCESS'는 꽤 쓸모가 없습니다. – effeffe

답변

1

당신은 매개 변수로 제공하려는 경우 결과를 저장하는 time() 기능을 위해 메모리를 할당해야합니다 다음은 C89 코드입니다. 변수를 스택에 선언하거나 malloc()을 호출하십시오. NULL을 매개 변수로 입력하면 반환 된 값을 검색 할 수도 있습니다. 당신이 그 주소로 결과를 저장하는 time_ttime()에의 주소를 전달하는 기능 time() 프로토 타입 here

+0

으악. 내 잘못이야. 감사합니다. 5 초마다 메모를 편집 할 수 있습니다. 알약 인 것에 대해 유감스럽게 생각합니다. – Draeton

+0

아니요. 이 함수는 명시 적으로 malloc()을 호출하거나 스택에 선언 된 변수를 사용하여 "할당"된 메모리에 대한 포인터를 가져옵니다 (첫 번째 예제에서와 같이). undefined time()에 포인터를 지정하면 메모리의 정의되지 않은 위치에 무언가를 쓰려고 시도하지만 그렇게해서는 안됩니다. – koopajah

2

time_t current_time_since_epoch; 
time(&current_time_since_epoch); 
// or 
current_time_since_epoch = time(NULL); 
// or 
time_t* timePtr = (time_t*) malloc(sizeof(time_t)); 
time(timePtr); 
// ... 
free(timePtr); 

더 많은 정보를 원하시면. 결과를 저장하기 위해 메모리를 할당하지 않았으므로 (초기화되지 않은 포인터를 선언 한 것 모두) 정의되지 않은 동작이 발생합니다. NULLtime에 전달하면 값이 반환됩니다.

time_t current_time_since_epoch = time(NULL); 
관련 문제