I’ve recently uptaken rewriting argument handling code I began to create, and I’ve added utilization of dynamic memory management functions (malloc, realloc, free), but after adding such I am getting strange crashes when I attempt to execute an example.
The following is output from my program:
charles@draton-generico:~/Documents/C/C89/SDL_Work/2D-game-base$ ./game-base-02-alt-2 –l
Successfully exited argument catching loop.
==>Continuing execution.
* glibc detected ./game-base-02-alt-2: realloc(): invalid next size: 0x000000000157c010 **
After outputting this much it just hangs.
The following is my code:
/*
* 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);
}
I’d love to turn this into a learning experience.
malloc()andrealloc()have no idea about what kind of data type you’re going to store in the memory pointed to by the returned pointers. So they just allocate some bytes – and they don’t magically multiply their arguments bysizeof(int). So what you want is:and the alike with
realloc().