I am new to c
how can I test that malloc() has successfully giving 26 bytes of memory
example t=(char*)malloc(26 * sizeof(char));
how can i test this function
thanks
I am new to c
how can I test that malloc() has successfully giving 26 bytes of memory
example t=(char*)malloc(26 * sizeof(char));
how can i test this function
thanks
If malloc fails then it will return a NULL pointer, otherwise you got your memory:
And please don't cast malloc, it's not needed and can hide other problems.Code:var = malloc ( 26 * sizeof ( char ) ); if ( var != NULL ) { /* It's good, work with it. */ } else { /* Bad, handle the error */ }
-Prelude
My best code is written with the delete key.
You make sure that it's return value is not NULL. If it is, it failed.
Code:if ((ptr = malloc(26)) == NULL) { printf("memory problem!"); return 1; }
When all else fails, read the instructions.
If you're posting code, use code tags: [code] /* insert code here */ [/code]
Thank you all for the help
But is there a way to print how much memory was assigned?
>But is there a way to print how much memory was assigned?
You can't be sure exactly how much malloc gave you since it can and often does give you slightly more than you ask for and sizeof won't work with dynamic memory. So maintain a size variable which holds the size you gave malloc and use that.
-Prelude
My best code is written with the delete key.
thanks