LoginSignup
1
0

More than 5 years have passed since last update.

なぜか実行するとエラーになる

Last updated at Posted at 2012-12-26

mingw の gcc version 4.6.2。OS は Windows7 64bit Pro版 で
次のコードを gcc -O3 -o hoge hoge.c でコンパイルすると
コンパイルが通って実行ファイルもちゃんと動く。

hoge.c
#include <stdio.h>

typedef struct{
    int value;
} HOGE;

void piyo(HOGE *hoge);

int main(void)
{
    HOGE hoge;
    hoge.value = 100;
    piyo(&hoge);
    return(0);
}

void piyo(HOGE *hoge)
{
    printf("%d\n", hoge->value);
}

でも、次のコードを gcc -O3 -o hoge1 hoge1.c でコンパイルするとコンパイルは通る。
ただ、実行ファイルを実行するとなぜか Windows7 のPro版が「hoge1.exe は動作を停止しました」
とかのエラーダイアログを出力する。
なんでだろう? たしか gcc の version が 3.4.5 の時は両方ちゃんと動いてたはず。

hoge1.c
#include <stdio.h>

typedef struct{
    int value;
} HOGE;

void piyo(HOGE *hoge);

int main(void)
{
    HOGE *hoge;
    hoge->value = 100;
    piyo(hoge);
    return(0);
}

void piyo(HOGE *hoge)
{
    printf("%d\n", hoge->value);
}

Linda_pp さんにコメントを頂きました。
ポインタ変数の宣言だけしていて、そのポインタ変数が指すべき実体を定義していなかったので、未定義の動作になっているとのこと。
修行が足らんです。

コメントそのままの改修を入れたら、きっちり動きました。

hoge2.c
#include <stdio.h>
#include <stdlib.h>

typedef struct{
    int value;
} HOGE;

void piyo(HOGE *hoge);

int main(void)
{
    HOGE *hoge = (HOGE*)malloc(sizeof(HOGE));  // <= ここ改修
    hoge->value = 100;
    piyo(hoge);
    return(0);
}

void piyo(HOGE *hoge)
{
    printf("%d\n", hoge->value);
}
$ gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=c:/tools/mingw/bin/../libexec/gcc/mingw32/4.6.2/lto-wrapper.exe
Target: mingw32
Configured with: ../gcc-4.6.2/configure --enable-languages=c,c++,ada,fortran,objc,obj-c++ --disable-sjlj-exceptions --with-dwarf2 --enable-shared --enable-libgomp --disable-win32-registry --enable-libstdcxx-debug --enable-version-specific-runtime-libs --build=mingw32 --prefix=/mingw
Thread model: win32
gcc version 4.6.2 (GCC)
1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0