本文へスキップ
製品デスクトップツールTASTECAD図面の確認TASTEFILESファイル管理TASTEFTPファイル転送TASTESSHリモートワークスペースTASTEZIP圧縮と展開開発ツールTASTECODERust 統合開発環境TASTESTUDIO統合開発・テスト環境TASTEETLデータ統合(ETL)サーバーTASTEREMOTEリモートデスクトップサーバーTASTEGEO空間情報サーバーTASTEMAILメールワークスペースはじめるダウンロードドキュメント購入すべての製品
マーケットプレイス
ニュース
技術ニュース今日の開発ニュース開発ドキュメントプログラミング言語RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWebフロントエンド フレームワークNext.jsReactVue.js · NuxtSvelteKitAngularサーバー フレームワークSpring BootDjangoFastAPIASP.NET CoreNestJS · Expressアプリ・デスクトップ フレームワークTauriFlutterReact NativeElectronアルゴリズムアルゴリズムの基礎主要アルゴリズム発展アルゴリズム実務のアルゴリズム
コミュニティプロジェクト開発ログプロンプトAIツールの問題ショーケースコミュニティガイド
協業技術移転ウェブサイト構築デスクトップアプリ構築リリース・決済パイプライン販売パートナーお問い合わせ
サービスリモートデスクトップインストールパッケージのカスタマイズ
TASTEDEV
製品

デスクトップツール

TASTECAD複雑な図面を、軽やかにひらくTASTEFILES必要なファイルだけを、最速でTASTEFTPファイルが行き交う、いちばん端正な道TASTESSHサーバーとあなたを、より確かにつなぐTASTEZIPより速くまとめ、より安全にひらく

開発ツール

TASTECODERust アプリの編集・ビルド・デバッグ・テストまでひとつのウィンドウでTASTESTUDIO編集からリモートテスト、承認した AI 修正までTASTEETL値を見ながら、データを運ぶ

サーバー

TASTEREMOTE自社サーバーで運用するリモートデスクトップTASTEGEOGeoServer 互換の空間情報サーバーを Rust で作り直しますTASTEMAILメールの主導権を、もう一度自分の手に

はじめる

ダウンロード全製品の最新版ドキュメント各製品の使い方購入サブスクリプション・永久ライセンスすべての製品全製品を一覧で
すべての製品
マーケットプレイスニュース
技術

ニュース

今日の開発ニュース言語・フレームワーク・GitHub・AI の公式発表開発ドキュメント言語・フレームワーク・アルゴリズムのガイド

プログラミング言語

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

フレームワーク

Webフロントエンド フレームワークNext.jsReactVue.js · NuxtSvelteKitAngular
サーバー フレームワークSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
アプリ・デスクトップ フレームワークTauriFlutterReact NativeElectron

アルゴリズム

アルゴリズムの基礎計算量解析 · ソート · 探索 · 基本データ構造 · 木構造とヒープ主要アルゴリズムグラフ探索 · 最短経路と最小全域木 · 動的計画法 · 貪欲法 · 分割統治法 · バックトラッキング発展アルゴリズム文字列アルゴリズム · 数学と整数論 · ビット演算 · セグメント木 · Union-Find実務のアルゴリズムコーディング面接対策 · LRUキャッシュ · レート制限 · コンシステントハッシュ法
開発ドキュメントをすべて見る
コミュニティ
プロジェクトビルダーと作品を探す開発ログ決定と試行錯誤プロンプト再利用できる指示AIツールの問題Claude・Codex・Gemini の問題と回避策ショーケース完成した成果コミュニティガイドオープンにつくる方法
協業
技術移転Rust・egui でネイティブアプリを作るウェブサイト構築10言語、アカウント、ドキュメントとダウンロードデスクトップアプリ構築Rust・egui、WebView なしリリース・決済パイプライン署名・MSI・deb・rpm・AppImage・ハッシュ販売パートナー紹介して決済額の30%お問い合わせ構築・提携・投資のご相談
サービス
リモートデスクトップブラウザから自分のパソコンへインストールパッケージのカスタマイズ必要な機能だけ、設定は事前に
購入
JA
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
ログイン
ログイン
TASTEDEV

小さなツールから、より良い開発へ。

support@tastedev.netTASTEDEVを支援
製品製品ラインナップ購入ドキュメントダウンロードマーケットプレイスサポート
コミュニティプロジェクト開発ログプロンプトAIツールの問題ショーケース
ポリシープライバシーポリシー利用規約サブスクリプション規約返金ポリシーコミュニティガイドライン
アカウントログイン新規登録
訪問者
今日
012345678901234567890123456789012345678901234567890123456789
昨日
012345678901234567890123456789012345678901234567890123456789
累計閲覧
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
商号
GXSOFT
代表者
CHOI YOUNG GU
事業者登録番号
853-44-00368
所在地
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
電話
+82-10-4404-1523
メール
whitecalvin@tastedev.net
個人情報保護責任者
CHOI YOUNG GU

© 2026 TASTEDEV製品情報は検証済みの開発ソースに基づいています。リリース・改善中

C ドキュメント
C
Getting StartedSyntax BasicsTypes and DataModules and LibrariesErrors and TestingKey Concepts: Pointers and Memory
ディスカッション

C ガイド · 5/6

Errors and Testing

この章は現在、英語でのみ提供しています。

C has no exceptions. Functions report failure through return values and errno, and the caller must check every time. This chapter also covers assert, sanitizers, and lightweight unit testing.

Reporting errors with return codes

By convention, return 0 on success and a negative code on failure, passing the real result back through a pointer (an out-parameter). Pointer-returning functions signal failure with NULL.

#include <stdio.h>

enum { OK = 0, ERR_DIV_ZERO = -1, ERR_NULL = -2 };

int safe_divide(int a, int b, int *out) {
    if (out == NULL) return ERR_NULL;
    if (b == 0) return ERR_DIV_ZERO;
    *out = a / b;
    return OK;
}

int main(void) {
    int result;
    int rc = safe_divide(10, 0, &result);
    if (rc != OK) {
        fprintf(stderr, "division failed (code %d)\n", rc);
        return 1;
    }
    printf("%d\n", result);
    return 0;
}

Ignored return values are among the most common C bugs. If a call can fail, check it before using what it produced.

errno

Many standard library functions return a sentinel such as NULL, -1, or EOF on failure and store the reason in errno from <errno.h>. strerror(errno) and perror turn the code into a readable message.

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {
    if (argc < 2) {
        fprintf(stderr, "usage: %s <file> [number]\n", argv[0]);
        return 1;
    }
    FILE *fp = fopen(argv[1], "r");
    if (fp == NULL) {
        fprintf(stderr, "cannot open %s: %s\n", argv[1], strerror(errno));
        return 1;
    }
    fclose(fp);

    if (argc > 2) {
        char *end;
        errno = 0;                         /* reset before calling strtol */
        long n = strtol(argv[2], &end, 10);
        if (errno == ERANGE) {
            fprintf(stderr, "number out of range\n");
        } else if (end == argv[2] || *end != '\0') {
            fprintf(stderr, "not a number\n");
        } else {
            printf("n = %ld\n", n);
        }
    }
    return 0;
}

errno only means something after a failure, and successful calls do not reset it, so check the return value first. When the return value alone cannot signal an error, as with strtol, set errno = 0 beforehand. Avoid atoi, which cannot report bad input at all.

assert and defensive checks

assert from <assert.h> verifies an assumption that should always hold; if it fails, it prints the file and line and aborts. Defining NDEBUG compiles every assert away, so anything that can legitimately go wrong at run time, such as user input or file contents, needs a real check instead.

この章について質問がありますか?
前の章Modules and Libraries次の章Key Concepts: Pointers and Memory
if
#include <assert.h>
#include <stdlib.h>
#include <string.h>

/* internal helper: caller obligations are checked with assert */
static void copy_ints(int *dst, const int *src, size_t n) {
    assert(dst != NULL && src != NULL);
    memcpy(dst, src, n * sizeof *dst);
}

/* public API: validate external input and report errors */
int *duplicate(const int *src, size_t n) {
    if (src == NULL || n == 0) return NULL;
    int *copy = malloc(n * sizeof *copy);
    if (copy == NULL) return NULL;        /* out of memory */
    copy_ints(copy, src, n);
    return copy;
}

When a function acquires several resources, a common idiom is to goto a single cleanup label on failure instead of repeating release code at every exit.

Sanitizers

Memory and overflow bugs often look harmless until they corrupt something far away. GCC and Clang sanitizers catch them the moment they happen.

  • AddressSanitizer (ASan) finds buffer overflows, use-after-free, double free, and leaks.
  • UndefinedBehaviorSanitizer (UBSan) finds signed overflow, division by zero, invalid shifts, and other undefined behavior.
gcc -std=c17 -g -O1 -fno-omit-frame-pointer \
    -fsanitize=address,undefined bug.c -o bug
./bug
// bug.c
#include <stdlib.h>
#include <limits.h>

int main(void) {
    int *a = malloc(4 * sizeof *a);
    a[4] = 1;              /* ASan: heap-buffer-overflow */
    free(a);

    int x = INT_MAX;
    x = x + 1;             /* UBSan: signed integer overflow */
    return x == 0;
}

The report points at the offending line and, for heap errors, the allocation site. Sanitized builds are slower, so use them for development and tests, not releases. MSVC supports ASan too, via /fsanitize=address.

A minimal unit test

The standard library ships no test framework, but a small test program gets you surprisingly far. Count failures and report through the exit status, and Make, CMake, and any CI system can use it directly.

// test_mathutil.c
#include <stdio.h>
#include "mathutil.h"

static int failures = 0;

#define CHECK(cond) do { \
    if (!(cond)) { \
        fprintf(stderr, "%s:%d: failed: %s\n", __FILE__, __LINE__, #cond); \
        failures++; \
    } \
} while (0)

int main(void) {
    CHECK(clamp(5, 0, 10) == 5);
    CHECK(clamp(-3, 0, 10) == 0);
    CHECK(clamp(42, 0, 10) == 10);
    printf("%s\n", failures ? "FAILED" : "OK");
    return failures ? 1 : 0;
}

With CMake, add enable_testing() and add_test(NAME mathutil COMMAND test_mathutil), then run ctest from the build directory. As the suite grows, consider frameworks such as Unity, cmocka, or Check, and build tests with sanitizers to catch memory errors in the same run.

Summary

  • Report errors through return values (0 for success, negative or NULL for failure) and always check them.
  • Read errno only after confirming a failure, and format it with strerror or perror.
  • assert checks programmer assumptions; validate external input with ordinary if statements.
  • Use -fsanitize=address,undefined during development to catch memory errors and undefined behavior.
  • Start with a tiny test program that reports through its exit status, and adopt a framework when you need one.

コメント 0件

人気のコメント順新しい順

ログイン · ログインするとコメントできます。