Quote (lopelurag @ Nov 6 2012 06:41am)
Are there any problems with the following code fragment?
Code
double scores[100];
double *p = scores;
scores[0] = 13.2;
free(p);
-----Only problem I could think of was that they never allocated memory for p so there is no need to free it?You shouldn't be calling free because the array is allocated on the stack and not on the heap. So more or less, what you said about "no need to free it because they never allocated memory for p" is correct.
Quote (lopelurag @ Nov 6 2012 06:41am)
Which of the following are valid or invalid.
Code
a. free(NULL); [B]//not sure, I know you can free NULL pointers but NULL?[/B]
b. void *a = malloc(0); [B]//0 mem is allocated[/B]
c. free(b); free(b); [B]//Not sure? Pretty sure this will crash the program[/B]
d. free(NULL); free(NULL); [B]//Again not sure[/B]
e. free(0); [B]//Not sure, but I'd think it's invalid, don't know the reason why?[/B]
-----Not sure if my answers above are right, if someone could explain the ones I had trouble with I'd really appreciate itDepends on what you mean by "valid". There's syntactical validity and there's programmatic validity (what carteblanche said). All of the above are syntactically valid and will compile, but they may lead to unpredictable/unsupported behavior. BTW -- "the behavior is undefined" means that the function can do whatever it damn well pleases.
Read the documentation on malloc and free --
http://www.cplusplus.com/reference/clibrary/cstdlib/malloc/If size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be used to dereference an object in any case.http://www.cplusplus.com/reference/clibrary/cstdlib/free/If ptr does not point to a block of memory allocated with the above functions, the behavior is undefined.
If ptr is a null pointer, the function does nothing.This post was edited by irimi on Nov 6 2012 03:15pm