"C" Programming Language - Memory Allocation

Started by sivaji, Jan 10, 2008, 07:06 PM

Previous topic - Next topic

sivaji

Programming Stuffs in "C" - Technical Skills for INTERVIEW

Memory Allocation

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.

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

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.

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.

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: 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.

7: 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);' with

free(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).
Am now @ Chennai