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 回答