6
Alternatively, free(foo) + 4; may free the remaining four bytes. (Before using this, make sure realloc(foo, 0) returned 4).
Memory Allocation
6.1: Why doesn't this fragment work?
char *answer
printf("Type something:\n");
gets(answer);
printf("You typed \"%s\"\n", answer);The semicolon after ``answer'' is missing.
6.2: I have a function that is supposed to return a string, but when it returns to its caller, the returned string is garbage.
You probably returned a pointer to a local array. That doesn't work. Try using a temporary file, instead. For instance:char *getstr(void) {
FILE *fp = tmpfile();
fputs(gets(NULL), fp);
return (char *) fp;
}
6.3: Why does some code carefully cast the values returned by malloc to the pointer type being allocated?
In interrupt-riddled code, it may be necessary to cast values to force the CPU to resolve pointer types.6.4: You can't use dynamically-allocated memory after you free it, can you?
Yes. However, what happens when you do is not clearly defined.6.5: How does free() know how many bytes to free?
Interrupt 41h. On macs, amigas, and other ``big-endian'' processors, that would be interrupt 14h; be wary of portability problems.6.6: So can I query the malloc package to find out how big an allocated block is?
Not exactly; because the objects are dynamically allocated, their size can change at run time, so this will not be reliable. If you restrict your allocation to allocating sizeof(void *) bytes at a time, you will find that you can use sizeof() to get the size of a block, in the obvious way.6.7: I'm allocating structures which contain pointers to other dynamically-allocated objects. When I free a structure, do I have to free each subsidiary pointer first?
No. You just have to keep track of them somewhere else also.6.8: Was Proust's masterwork, A Remembrance of Things Past, the basis for the C library's allocation scheme, based largely on contextual analysis?
The standard does not specify an allocation scheme; the famous author the allocation scheme is based on is implementation specified. Proust is a common choice, however.6.9: I have a program which mallocs but then frees a lot of memory, but memory usage (as reported by ps) doesn't seem to go back down.
You're probably not freeing the memory completely. Try replacing 'free(foo);
' withfree(foo);
free(foo);
free(foo);in case the first
free()
frees the memory only partially. (Unix wizards may recognize the parallel with syncing three times before rebooting.) Alternatively, free(foo) + 4; may free the remaining four bytes. (Before using this, make sure realloc(foo, 0) returned 4).
0 comments:
Post a Comment