0

私は最近、作成し始めた引数処理コードの書き換えに取り掛かり、動的メモリ管理関数 (malloc、realloc、free) の利用を追加しましたが、そのようなものを追加した後、例を実行しようとすると奇妙なクラッシュが発生します。

以下は私のプログラムからの出力です:

charles@draton-generico:~/Documents/C/C89/SDL_Work/2D-game-base$ ./game-base-02-alt-2 --l

引数キャッチ ループを正常に終了しました。

==>実行を継続します。

* glibc が検出されました./game-base-02-alt-2: realloc(): 無効な次のサイズ: 0x000000000157c010 * *

これだけ出力した後、ハングします。

以下は私のコードです:

/* 
 * CREATED BY:  Charles Edwin Swain 3rd
 * DATE OF PROJECT BEGINNING:  28/1/2013
 */

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

int main(int argc, char** argv)
{
int* bse = malloc(3 + 5 + 5 + argc);
if (bse == NULL)
{
    if (fprintf(stderr, "Call to malloc failed, bse = NULL.\n==>Will now exit.\n") <= 0) exit(-2);
    exit(-1);
}
*(bse + 0) = 0;
while (*(bse + 0) < (3 + 5 + 5 + argc))
{
    *(bse + *(bse + 0)) = 0;
    *(bse + 0) = *(bse + 0) + 1;
}
*(bse + 0) = 0;
*(bse + 1) = -1;
/*THIS DETERMINES THE SIZE OF THE LARGEST ARGV CHARACTER STRING.*/
while (*(bse + 3) < argc)
{
    while (*(bse + 4) != -1)
    {
        if (argv[*(bse + 3)][*(bse + 4)] == '\0')
        {
            if ((*(bse + 4) + 1) > *(bse + 5)) *(bse + 5) = *(bse + 4) + 1;
            *(bse + 4) = -1;
        }
        else if (*(bse + 4) == 32766)
        {
            *(bse + 3 + 5 + 5 + *(bse + 3)) = 1;
            *(bse + 4) = -1;
        }
        else *(bse + 4) = *(bse + 4) + 1;
    }
    *(bse + 3) = *(bse + 3) + 1;
    *(bse + 4) = 0;
}
*(bse + 3) = 0;
/*ENSURING THAT SPACE FOR RETREIVED ARGV CHARACTER STRINGS IS AT LEAST THE SIZE OF THE LARGEST CHECKED FOR SPECIFIC STRING ON LINE BELOW.*/
if (*(bse + 5) < 10) *(bse + 5) = 10;
/*THIS IS (IN SOME CASES WAS) THE BIG ARGV CATCHING LOOP.*/
/*ERASED CONTENTS OF, AM REWRITING CODE.*/
while (*(bse + 3) < argc)
{
    *(bse + 3) = argc;
}
if (fprintf(stdout, "Successfully exited argument catching loop.\n==>Continuing execution.\n") <= 0)
{
    while ((*(bse + 1) <= 0)&&(*(bse + 2) < 50))
    {
        *(bse + 1) = fprintf(stderr, "A function (fprintf) failed when outputting a notification informing of having 'properly' left the argument catching loop.\n==>Will now exit.\n");
        *(bse + 2) = *(bse + 2) + 1;
    }
    free(bse);
    exit(-1);
}

/*SET DEFAULTS HERE*/

bse = realloc(bse, 3);
if (bse == NULL)
{
    if (fprintf(stderr, "Call to realloc failed, bse = NULL.\n==>Will now exit.\n") <= 0) exit(-2);
    exit(-1);
}

/*END OF CODE.*/
free(bse);
exit(0);
}

これを学習体験に変えたいと思います。

4

1 に答える 1

2

malloc()またrealloc()、返されたポインターが指すメモリに格納するデータ型の種類についてもわかりません。したがって、彼らはいくつかのバイトを割り当てるだけであり、魔法のように引数に を掛けることはありませんsizeof(int)。だからあなたが欲しいのは:

int *bse = malloc((3 + 5 + 5 + argc) * sizeof(*bse));

と同様realloc()

于 2013-02-11T19:05:09.490 に答える