Fullbright Fullbright - 1 year ago 40
C Question

Why does this C programm crash?

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);


I am thankful for any advice!

Answer Source

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


You have been modifying the value contained in this pointer:

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

Do instead:

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download