0

関数「time」と「time.h」の他の関数を使用するコードがあり、「time」は「time」ごとにNULLを返します(笑、面白くはありませんが、これは「time」に費用がかかります。そのようなものへの注意)そのようなものが再実行されます。これが昨日始まったばかりであるという事実は奇妙です。似ているが欠けている(私はそれに追加している)コードで同じ関数を以前に使用したことは問題ないことが証明されました。以下はC89コードです。

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

2 に答える 2

2

aのアドレスを渡すと、そのアドレスに結果が保存されますtime_ttime()結果を格納するためのメモリを割り当てなかったため(初期化されていないポインタを宣言するだけでした)、未定義の動作が発生します。に渡すだけNULLtime、値が返されます。

time_t current_time_since_epoch = time(NULL);
于 2012-12-15T18:37:17.027 に答える
1

time()結果をパラメータとして提供する場合は、結果を保存するために関数にメモリを割り当てる必要があります。スタックで変数を宣言するか、を呼び出しますmalloc()。パラメータとして指定すると、戻り値を取得することもできNULLます。

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);

time()関数プロトタイプの詳細については、こちらをご覧ください

于 2012-12-15T18:35:51.860 に答える