Note that there are some explanatory texts on larger screens.

plurals
  1. POmalloc: error checking and freeing memory
    text
    copied!<p>I'm using malloc to make an error check of whether memory can be allocated or not for the particular array z1. ARRAY_SIZE is a predefined with a numerical value. I use casting as I've read it's safe to do so.</p> <pre><code>long double *z1 = (long double *)malloc(sizeof (long double) * ARRAY_SIZE); if(z1 == NULL){ printf("Out of memory\n"); exit(-1); } </code></pre> <p>The above is just a snippet of my code, but when I add the error checking part (contained in the if statement above), I get a lot of compile time errors with visual studio 2008. It is this error checking part that's generating all the errors. What am I doing wrong?</p> <p>On a related issue with malloc, I understand that the memory needs to be deallocated/freed after the variable/array z1 has been used. For the array z1, I use:</p> <pre><code>free(z1); z1 = NULL; </code></pre> <p>Is the second line <code>z1 = NULL</code> necessary?</p> <p>I get 102 errors...well MVS2008 stops the errors at 102. The errors are of type:</p> <pre><code>error C2143: syntax error : missing ';' before 'type' error C2065: 'L' : undeclared identifier // this error repeats for all my identifiers </code></pre> <p>and this points right after the closing } in the if statement.</p> <p>ARRAY_SIZE is quite large. I define it as</p> <pre><code>#define ARRAY_SIZE 2500001 </code></pre> <p>My full above code is too long. But I have a smaller code which is giving me the same behavior. Sorry for the formatting. I can't seem to get it right.</p> <pre><code>#include stdio.h //note I have the actual &lt; &gt; in my code #include stdlib.h #include math.h #define ARRAY_SIZE 11 #define VECTOR_SIZE 5 main() { long double *z = (long double*) malloc(sizeof (long double) * ARRAY_SIZE); if(z == NULL){ printf("Out of memory\n"); exit(-1); } long double *k = (long double*) malloc(sizeof (long double) * VECTOR_SIZE); int i; long double A, B; void f(long double fa[], long double fb[], long double fA, long double fB); A = 0.5; B = 2; for(i = 0; i &lt; VECTOR_SIZE; i++){ k[i] = 0; } k[1] = 4; k[2] = 8; for(i = 0; i &lt; ARRAY_SIZE; i++){ z[i] = 0; } z[1] = 5; f(k, z, A, B); free(z); free(k); z = NULL; k = NULL; } void f(fa, fb, fA, fB) long double fa[], fb[], fA, fB; { fa[0] = fb[1]* fA; fa[1] = fa[1] - 1; fb[0] = 2* fB - fa[2]; printf("fa[2] is 8 and is the same as *[fa + 2] and is %3.3Le\n", *(fa + 2)); printf("\nAddress of &amp;fa[2] is %x\n", &amp;fa[2]); printf("same address is fa + 2 is %x\n", fa + 2); return; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload