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?

Toolbox97
  • 76
  • 7
  • 1
    [Please don't cast the result of `malloc()`](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858). – Quentin Feb 07 '15 at 23:03
  • If you change `moves` without `free`ing its memory, that's a memory leak. From the given code, though, it looks like the memory you allocated to `final` is wasted. –  Feb 07 '15 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 – Toolbox97 Feb 07 '15 at 23:06

1 Answers1

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];
Jack
  • 131,802
  • 30
  • 241
  • 343
  • 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 []. – Toolbox97 Feb 07 '15 at 23:09
  • 1
    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. http://programmers.stackexchange.com/questions/99445/is-micro-optimisation-important-when-coding – Jack Feb 07 '15 at 23:14
  • i am now using the [] operator and my program is now crashing – Toolbox97 Feb 07 '15 at 23:18
  • The issue was malloc(size+1) was allocating one forth the memory i needed because they are all ints – Toolbox97 Feb 07 '15 at 23:20
  • @Toolbox97 using the pattern `p = calloc(N, sizeof *p);` or `p = malloc(N * sizeof *p);` avoids that sort of problem – M.M Feb 07 '15 at 23:23