-1

I have written the following code, however I get a crash (without warnings or errors) and do not know the cause:

const int N = 1000;

int main(){   
    int *pI = calloc(N,sizeof(int));
    for (int i=0;i<N;i++) {
        *(pI++) = (i+1);
    }
    free(pI);

    return EXIT_SUCCESS;
}

I am thankful for any advice!

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Fullbright
  • 11
  • 1
  • 4
    Hint: when your program crashes, look into using a debugger. Or at least: put up print statements that tell you **where** exactly you crash. – GhostCat May 23 '17 at 07:04
  • 4
    You modify `pI`, so you can't call `free(pI)`, since it's no longer a pointer to a valid allocation. – Paul R May 23 '17 at 07:05

1 Answers1

4

You are not releasing the original pointer received from calloc():

 free(pI);

You have been modifying the value contained in this pointer:

*(pI++) = (i+1);

Do instead:

int *p = calloc(N,sizeof(int));
int *pI = p;
// ...
free(p);

That is, save the value returned from calloc() and then pass it to free() when you don't need the allocated memory anymore.

JFMR
  • 23,265
  • 4
  • 52
  • 76