0

Simple question, but the other similar questions on here are don't deal with this specific case, or so i could find.

int * moves;
moves = malloc(540); //540 is the most i will ever need, usually less
someFunctionThatFillsSomeOfThoseSlots // also returns how many slots were used

int * final = malloc(size+1);

for(x = 0; x < size; x++, final++, moves++)
    final = moves;
final -= size;

how should i be freeing the memory of moves, after having changed its pointer?

3
  • 1
    Please don't cast the result of malloc(). Commented Feb 7, 2015 at 23:03
  • If you change moves without freeing its memory, that's a memory leak. From the given code, though, it looks like the memory you allocated to final is wasted. Commented Feb 7, 2015 at 23:03
  • Should i make another pointer to the begining of moves, chage that new pointer, and then free(moves)? i know it is a memory leak how it is now Commented Feb 7, 2015 at 23:06

1 Answer 1

3

This

final = moves;

reassigns the variable final to moves, so the just allocated pointer is lost in the universe of leaked memory.

What you probably meant is:

*final = *moves;

which assigns to the location pointed by final, the value pointed by moves.

But this doesn't solve your problem, since if you lose the address that malloc gave initially for moves you can't free it. You could do free(moves - size) but it's just complicated.

Why don't you just use [] operator?

for (int x = 0; x < size; ++x)
  final[x] = moves[x];
Sign up to request clarification or add additional context in comments.

5 Comments

I'm converting a ChessAI from java to C in an attempt to make it faster. I was under the impression that iterating over the points was faster than doing it with [].
To be under the impression of something is meaningless when developing software. The only meaningful thing is to verify if something is really a bottleneck, measure it and then draw conclusions. programmers.stackexchange.com/questions/99445/…
i am now using the [] operator and my program is now crashing
The issue was malloc(size+1) was allocating one forth the memory i needed because they are all ints
@Toolbox97 using the pattern p = calloc(N, sizeof *p); or p = malloc(N * sizeof *p); avoids that sort of problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.