我最近已经开始重写我开始创建的重写参数处理代码,并且我添加了动态内存管理函数(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);
}
我很想把它变成一种学习经历。
答案 0 :(得分:2)
malloc()
和realloc()
不知道您要将哪种数据类型存储在返回指针所指向的内存中。所以他们只是分配一些字节 - 并且他们不会将他们的参数神奇地乘以sizeof(int)
。所以你想要的是:
int *bse = malloc((3 + 5 + 5 + argc) * sizeof(*bse));
和realloc()
一样。