I am trying to decrease the size of a malloc array, but it is throwing -1073741819 (0xC0000005) when I realloc a smaller size for the malloc.
typedef struct {
float reproduce_prob;
int mature;
int life;
int age;
char *direction;
int X;
int Y;
} slug;
slug *slugs = (slug *) malloc(sizeof(slug) * (slugCount 1));
int slugCount = 0;
if (slugCheck(theGrid, frogs[i])) {
int pos = feedFrog(frogs[i], slugs, slugCount);
for (int z = pos; z < slugCount - 1; z ) {
slugs[z] = slugs[z 1];
}
slugCount--;
slugs = realloc(slugs, sizeof(slugs) * (slugCount 1));
frogs[i].initHung = 0;
}
the slugCount is not zero.
CodePudding user response:
It is good practice to use obects not types in the sizeof
s. Also it is good to have distinct and meaningful type and variable names to avoid this kind mistakes. I would call slug
slugType
or slug_type
.
in this line you do not allocate enough space (assuming that the slug structure is larger than the pointer) as sizeof(slugs) is giving the size of the pointer to slug
:
slugs = realloc(slugs, sizeof(slugs) * (slugCount 1));
You also incorrectly use realloc as realloc may fail and you will have memory leak
slug *tmp;
tmp = realloc(slugs, sizeof(*tmp) * (slugCount 1));
if(tmp)
{
slugs = tmp;
}
else
{
/* error handling */
}
As a side note: do not cast the result of malloc
family functions. If Your code does not compile it means that you use C compiler to compile the C language code. It is not a good idea as C & C are different languages even if syntax looks similar.
CodePudding user response:
How does this code compile?
slug *slugs = (slug *) malloc(sizeof(slug) * (slugCount 1));
int slugCount = 0;
The compiler should be yelling at you for using slugCount
before it has been defined.
If this code is building it means you’ve already defined slugCount
in an enclosing scope, and its value may not be zero. That’s one problem.
You should always check the result of malloc
, calloc
, and realloc
. Are you certain that neither the malloc
nor realloc
call have returned NULL
?
This line is suspicious:
slugs = realloc(slugs, sizeof(slugs) * (slugCount 1));
sizeof(slugs)
gives you the size of the pointer, not the slug
type - you haven’t extended your array by one element, you’ve shrunk it by a whole helluva lot. You might want to change that to
slug *tmp = realloc( slugs, sizeof *slugs * (slugCount 1) );
You should always assign the result of realloc
to a temporary variable. realloc
will return NULL
if it can’t satisfy the request and leave the original buffer in place. However, if you assign that NULL
result back to your original pointer, you will lose your only reference to that memory.