2

次のコードは、セグメンテーション違反を引き起こします。実行可能ファイルの名前は「./struct」

#include <stdio.h>
#define VERSION_NUMBER_LEN 32
#define MAX_DESCRIPTION_COUNT 32
#define DESCRIPTION_LEN 128
int main(void)
{
    struct foo {
        char number[VERSION_NUMBER_LEN + 1];
        char description[MAX_DESCRIPTION_COUNT][DESCRIPTION_LEN];
    };

    struct foo asdf = {
        "1.1", { "clap", "clap", "stomp", NULL }
    };

    struct foo hjkl = {
        "1.2", { "clop", "clop", "stamp", NULL }
    };

    int i;
    printf( "%s\n", asdf.number );
    for( i = 0; (asdf.description)[i] != NULL; i++ ){
        printf( "\t%s\n", (asdf.description)[i]);
    }
    printf("\n");
    printf( "%s\n", hjkl.number );
    for( i = 0; (hjkl.description)[i] != NULL; i++ ){
        printf( "\t%s\n", (hjkl.description)[i]);
    }
}

出力は次のようになります。

1.1
    clap
    clap
    stomp






��
    N���~�����������ջ�����e���t�����������A���P���b���������������̽��㽊����,���V���g���y���������������̾��    ���k�����������Ͽ��迊�
    迊�





    ome/tiger
    56
    y
    vZxy/ssh
    ptop:/tmp/.ICE-unix/2710
    usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:~/bin:~/vitetris-0.3.6:/var/lib/gems/1.8/bin/
    baz
    GNOME_KEYRING_PID=2692
    t \w\n\$
    XDG_DATA_DIRS=/usr/share/gnome:/usr/local/share/:/usr/share/
    9a6bf0ef61ded7872065094fca55d1
    se
Segmentation fault

私はvalgrindを実行しました:

$ valgrind -v --leak-check=full --track-origins=yes ./struct  

<snip>

==15228== Conditional jump or move depends on uninitialised value(s)
==15228==    at 0x402605B: __GI_strlen (mc_replace_strmem.c:284)
==15228==    by 0x408A79E: vfprintf (vfprintf.c:1617)
==15228==    by 0x40912BF: printf (printf.c:35)
==15228==    by 0x8048910: main (in /home/tiger/dev/development/c/play/struct)
==15228==  Uninitialised value was created by a stack allocation
==15228==    at 0x4060B01: (below main) (libc-start.c:96)
==15228==
==15228== Conditional jump or move depends on uninitialised value(s)
==15228==    at 0x4026067: __GI_strlen (mc_replace_strmem.c:284)
==15228==    by 0x408A79E: vfprintf (vfprintf.c:1617)
==15228==    by 0x40912BF: printf (printf.c:35)
==15228==    by 0x8048910: main (in /home/tiger/dev/development/c/play/struct)
==15228==  Uninitialised value was created by a stack allocation
==15228==    at 0x4060B01: (below main) (libc-start.c:96)
==15228==
==15228== Invalid read of size 1
==15228==    at 0x4026058: __GI_strlen (mc_replace_strmem.c:284)
==15228==    by 0x408A79E: vfprintf (vfprintf.c:1617)
==15228==    by 0x40912BF: printf (printf.c:35)
==15228==    by 0x8048910: main (in /home/tiger/dev/development/c/play/struct)
==15228==  Address 0xbec1007c is not stack'd, malloc'd or (recently) free'd
==15228==
==15228==
==15228== Process terminating with default action of signal 11 (SIGSEGV)
==15228==  Access not within mapped region at address 0xBEC1007C
==15228==    at 0x4026058: __GI_strlen (mc_replace_strmem.c:284)
==15228==    by 0x408A79E: vfprintf (vfprintf.c:1617)
==15228==    by 0x40912BF: printf (printf.c:35)
==15228==    by 0x8048910: main (in /home/tiger/dev/development/c/play/struct)
==15228==  If you believe this happened as a result of a stack
==15228==  overflow in your program's main thread (unlikely but
==15228==  possible), you can try to increase the size of the
==15228==  main thread stack using the --main-stacksize= flag.
==15228==  The main thread stack size used in this run was 8388608.
==15228== Syscall param write(buf) points to uninitialised byte(s)
==15228==    at 0x4107DC3: __write_nocancel (syscall-template.S:82)
==15228==    by 0x40B0A1E: new_do_write (fileops.c:530)
==15228==    by 0x40B0D35: _IO_do_write@@GLIBC_2.1 (fileops.c:503)
==15228==    by 0x40B181C: _IO_file_overflow@@GLIBC_2.1 (fileops.c:881)
==15228==    by 0x40B2DED: _IO_flush_all_lockp (genops.c:849)
==15228==    by 0x40B3A4F: _IO_cleanup (genops.c:1010)
==15228==    by 0x41670F0: ??? (in /lib/tls/i686/cmov/libc-2.11.1.so)
==15228==    by 0x401F4F3: _vgnU_freeres (vg_preloaded.c:62)
==15228==    by 0xBEC0D5F7: ???
==15228==    by 0x408A79E: vfprintf (vfprintf.c:1617)
==15228==    by 0x40912BF: printf (printf.c:35)
==15228==    by 0x8048910: main (in /home/tiger/dev/development/c/play/struct)
==15228==  Address 0x402a054 is not stack'd, malloc'd or (recently) free'd
==15228==  Uninitialised value was created by a stack allocation
==15228==    at 0x4060B01: (below main) (libc-start.c:96)

<snip>

==15228== HEAP SUMMARY:
==15228==     in use at exit: 0 bytes in 0 blocks
==15228==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==15228==
==15228== All heap blocks were freed -- no leaks are possible
==15228==
==15228== ERROR SUMMARY: 7 errors from 4 contexts (suppressed: 12 from 7)
==15228==
==15228== 1 errors in context 1 of 4:
==15228== Syscall param write(buf) points to uninitialised byte(s)
==15228==    at 0x4107DC3: __write_nocancel (syscall-template.S:82)
==15228==    by 0x40B0A1E: new_do_write (fileops.c:530)
==15228==    by 0x40B0D35: _IO_do_write@@GLIBC_2.1 (fileops.c:503)
==15228==    by 0x40B181C: _IO_file_overflow@@GLIBC_2.1 (fileops.c:881)
==15228==    by 0x40B2DED: _IO_flush_all_lockp (genops.c:849)
==15228==    by 0x40B3A4F: _IO_cleanup (genops.c:1010)
==15228==    by 0x41670F0: ??? (in /lib/tls/i686/cmov/libc-2.11.1.so)
==15228==    by 0x401F4F3: _vgnU_freeres (vg_preloaded.c:62)
==15228==    by 0xBEC0D5F7: ???
==15228==    by 0x408A79E: vfprintf (vfprintf.c:1617)
==15228==    by 0x40912BF: printf (printf.c:35)
==15228==    by 0x8048910: main (in /home/tiger/dev/development/c/play/struct)
==15228==  Address 0x402a054 is not stack'd, malloc'd or (recently) free'd
==15228==  Uninitialised value was created by a stack allocation
==15228==    at 0x4060B01: (below main) (libc-start.c:96)
==15228==
==15228==

==15228== 1 errors in context 2 of 4:
==15228== Invalid read of size 1
==15228==    at 0x4026058: __GI_strlen (mc_replace_strmem.c:284)
==15228==    by 0x408A79E: vfprintf (vfprintf.c:1617)
==15228==    by 0x40912BF: printf (printf.c:35)
==15228==    by 0x8048910: main (in /home/tiger/dev/development/c/play/struct)
==15228==  Address 0xbec1007c is not stack'd, malloc'd or (recently) free'd
==15228==
==15228==
==15228== 1 errors in context 3 of 4:
==15228== Conditional jump or move depends on uninitialised value(s)
==15228==    at 0x402605B: __GI_strlen (mc_replace_strmem.c:284)
==15228==    by 0x408A79E: vfprintf (vfprintf.c:1617)
==15228==    by 0x40912BF: printf (printf.c:35)
==15228==    by 0x8048910: main (in /home/tiger/dev/development/c/play/struct)
==15228==  Uninitialised value was created by a stack allocation
==15228==    at 0x4060B01: (below main) (libc-start.c:96)
==15228==
==15228==
==15228== 4 errors in context 4 of 4:
==15228== Conditional jump or move depends on uninitialised value(s)
==15228==    at 0x4026067: __GI_strlen (mc_replace_strmem.c:284)
==15228==    by 0x408A79E: vfprintf (vfprintf.c:1617)
==15228==    by 0x40912BF: printf (printf.c:35)
==15228==    by 0x8048910: main (in /home/tiger/dev/development/c/play/struct)
==15228==  Uninitialised value was created by a stack allocation
==15228==    at 0x4060B01: (below main) (libc-start.c:96)
==15228==
--15228--
--15228-- used_suppression:     12 dl-hack3-cond-1
==15228==
==15228== ERROR SUMMARY: 7 errors from 4 contexts (suppressed: 12 from 7)

わかりました... valgrind が初期化されていないと表示するメモリ位置がいくつかありますが、その方法がわかりません... 構造体と内部の文字列は静的に定義され、構造体の各インスタンスは明示的に宣言されています。

2番目の構造体(hjkl)の要素の1つにアクセスすると、セグメンテーション違反が発生していると思います。

gdbを実行しました...

(gdb) p asdf
$1 = {number = "1.1", '\000' <repeats 29 times>, description = {"clap", '\000' <repeats 123 times>, "clap", '\000' <repeats 123 times>, 
"stomp", '\000' <repeats 122 times>, '\000' <repeats 127 times> <repeats 29 times>}}

(gdb) p hjkl
$2 = {number = "1.2", '\000' <repeats 29 times>, description = {"clop", '\000' <repeats   123 times>, "clop", '\000' <repeats 123 times>, 
"stamp", '\000' <repeats 122 times>, '\000' <repeats 127 times> <repeats 29 times>}}

セグメンテーション違反の原因がわかりません...

4

3 に答える 3

4

問題は、初期化文字列自体にあるのではなく、文字配列と文字ポインタの混同にあります。

特に、これはあなたが思っていることをしません:

struct foo asdf = {
    "1.1", { "clap", "clap", "stomp", NULL }
};

foo::description[][]文字列clap、clap、およびstomp OKで初期化していますが、2番目の文字列の最初の文字NULLをに割り当てています。これは、ポインターに割り当てる場合は機能しますが、意味がある場合は、文字配列に変換しようとしNULLており、文字へのポインターをに設定していませんNULL

ポインタがNULLであるかどうかを確認していますが、配列が事前に宣言されているため、NULLになることはありません。

だから単に変更する

for( i = 0; (hjkl.description)[i] != NULL; i++ ){

for( i = 0; *(hjkl.description)[i] != NULL; i++ ){

つまり、文字ポインタ自体の(不可能な)状態をチェックするのではなく、配列内の各文字列の最初のインデックスで文字をチェックしNULL ますNULL

最終的に完成したコード:

#include <stdio.h>
#define VERSION_NUMBER_LEN 32
#define MAX_DESCRIPTION_COUNT 32
#define DESCRIPTION_LEN 128
int main(void)
{
    struct foo {
        char number[VERSION_NUMBER_LEN + 1];
        char description[MAX_DESCRIPTION_COUNT][DESCRIPTION_LEN];
    };

    struct foo asdf = {
        "1.1", { "clap", "clap", "stomp", NULL }
    };

    struct foo hjkl = {
        "1.2", { "clop", "clop", "stamp", NULL }
    };

    int i;
    printf( "%s\n", asdf.number );
    for( i = 0; *(asdf.description)[i] != NULL; i++ ){
        printf( "\t%s\n", (asdf.description)[i]);
    }
    printf("\n");
    printf( "%s\n", hjkl.number );
    for( i = 0; *(hjkl.description)[i] != NULL; i++ ){
        printf( "\t%s\n", (hjkl.description)[i]);
    }
}

構造体が次のようになっている場合、コードは機能します。

struct foo {
    char number[VERSION_NUMBER_LEN + 1];
    char *description[MAX_DESCRIPTION_COUNT];
};

基本的に、(私が見ることができることから)実際の記述文字配列自体をハードコーディングする必要はなく、それらの数だけがあります。コードの残りの部分はそのままで機能します。

また、コンパイル中の警告を見ると(ほとんどの最新のCコンパイラと同じようにNULL定義されていると仮定し((void *)0)て)、次の警告が表示されます。

test.c:13:43: warning: incompatible pointer to integer conversion initializing
      'char' with an expression of type 'void *';
        "1.1", { "clap", "clap", "stomp", NULL }
                                          ^~~~
/usr/include/stdio.h:82:14: note: expanded from:
#define NULL __DARWIN_NULL
             ^
/usr/include/sys/_types.h:91:23: note: expanded from:
#define __DARWIN_NULL ((void *)0)
                      ^~~~~~~~~~~
test.c:13:43: warning: suggest braces around initialization of subobject
      [-Wmissing-braces]
        "1.1", { "clap", "clap", "stomp", NULL }
                                          ^~~~
/usr/include/stdio.h:82:14: note: expanded from:
#define NULL __DARWIN_NULL
             ^
/usr/include/sys/_types.h:91:23: note: expanded from:
#define __DARWIN_NULL ((void *)0)
                      ^~~~~~~~~~~
test.c:17:43: warning: incompatible pointer to integer conversion initializing
      'char' with an expression of type 'void *';
        "1.2", { "clop", "clop", "stamp", NULL }
                                          ^~~~
/usr/include/stdio.h:82:14: note: expanded from:
#define NULL __DARWIN_NULL
             ^
/usr/include/sys/_types.h:91:23: note: expanded from:
#define __DARWIN_NULL ((void *)0)
                      ^~~~~~~~~~~
test.c:17:43: warning: suggest braces around initialization of subobject
      [-Wmissing-braces]
        "1.2", { "clop", "clop", "stamp", NULL }
                                          ^~~~
/usr/include/stdio.h:82:14: note: expanded from:
#define NULL __DARWIN_NULL
             ^
/usr/include/sys/_types.h:91:23: note: expanded from:
#define __DARWIN_NULL ((void *)0)
                      ^~~~~~~~~~~
4 warnings generated.
于 2012-06-04T04:50:01.853 に答える
4

あなたのテスト(asdf.description)[i] != NULLは無効になり、真実になることはありません。修正は次のとおりです。

#include <stdio.h>
#define VERSION_NUMBER_LEN 32
#define MAX_DESCRIPTION_COUNT 32
#define DESCRIPTION_LEN 128
int main(void)
{
    struct foo {
        char number[VERSION_NUMBER_LEN + 1];
        char description[MAX_DESCRIPTION_COUNT][DESCRIPTION_LEN];
    };

    struct foo asdf = {
        "1.1", { "clap", "clap", "stomp", "" }
    };

    struct foo hjkl = {
        "1.2", { "clop", "clop", "stamp", "" }
    };

    int i;
    printf( "%s\n", asdf.number );
    for( i = 0; (asdf.description)[i][0] != 0; i++ ){
        printf( "\t%s\n", (asdf.description)[i]);
    }
    printf("\n");
    printf( "%s\n", hjkl.number );
    for( i = 0; (hjkl.description)[i][0] != 0; i++ ){
        printf( "\t%s\n", (hjkl.description)[i]);
    }
}
于 2012-06-04T04:47:29.823 に答える
3

マクロNULLは(少なくとも、最初にマクロを定義した人が)ポインター値としてのみ使用することを目的と#defineしていますが、多くの場合、単純なdで使用されます。

#define NULL 0

これはおそらく実装の場合です(図を除いて、ここでは重要ではありません。(void *)0以下の結果を変更せずに定義できますが、これにより、初期化子に関するコンパイル時の苦情が発生します)。for上記を念頭に置いて、最初のループを拡張してみましょう。

for (i = 0; (asdf.description)[i] != 0; i++) {
    printf( "\t%s\n", (asdf.description)[i]);
}

(補足:ここでの括弧は必要ありません。これは、.および添え字演算子のバインドがすでに括弧によって強制されているためです。)それぞれが(サイズの)asdf.description[i]1つの配列全体に名前を付けます。したがって、次のことを比較しています。DESCRIPTION_LENchar

<some array of char> != 0

配列オブジェクトの「値」は配列の最初の要素へのポインタであるため、これは次と同じ意味を持ちます。

&asdf.description[i][0] != 0

ポインター値(&asdf.description[i][0])を整数定数ゼロと比較すると、ポインターがNULL(「マクロNULLではなく、「システムのNULLポインターの内部表現」)であるかどうかがテストされます。有効なポインターのアドレスが0と等しくなることはありません。ループは(事実上)「永久に」実行されます(確かにi> = 32になるまで)。

最終的に、への呼び出しprintfはポインタ値を渡し、その結果、セグメンテーション違反が発生します。

おそらく、あなたが本当にやろうとしていたのは、最後の有効な配列に続く配列をすべてゼロバイトchar(または少なくとも最初のゼロバイト)で初期化することでした。その場合、ループテストは次のようになります。

asdf.description[i][0] != '\0'

DESCRIPTION_LENまた、32要素の配列(の配列のchar)が有効なarrays-of-charで完全に満たされている可能性を検討することもできます。この場合、以下を確認するi前にの値を確認する必要がありasdf.description[i][anything]ます。

i < MAX_DESCRIPTION_COUNT && asdf.description[i][0] != '\0'
于 2012-06-04T04:54:28.703 に答える