Memory as a Programming Concept in C and C++

4.1 What is the system heap and what it is used for?

4.2 Suppose our program requests just one memory allocation of a certain number of bytes. Checking the memory usage by our program during its execution shows that the dynamic memory increased more than we requested . Is this a sign of memory leaking?

4.3 Consider a simple program:

#include <stdio.h> #include <string.h> int main() { char* p; p = malloc(20); strcpy(p,"hello"); printf("%s\n",p); return 0; }

The C compiler gives the strange warning message "line 8: warning: assignment makes pointer from integer without a cast" , yet the program works correctly when executed. What is your explanation, considering that C compilers should allow void* to be stored in char* without complaining?

4.4 What is wrong with the following program?

#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char* p; p = realloc(p,100); strcpy(p,"hello"); p = realloc(p,200); strcat(p," and good bye"); return 0; }

4.5 In a program we allocated 20 bytes of memory using p = malloc(20) , yet we only need 10. For efficiency we decided to "return" a portion of the segment to the memory manager using free(&p[10]) . What will happen? Will it compile? If so, will the program execute correctly and cause memory segment fragmentation? Or will it not work as intended - the memory manager will not "accept" the memory and the program will continue executing? Or will the program be terminated ?

4.6 Will the following program crash? Always, sometimes, or never?

#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *p, *q; p = malloc(20); strcpy(p,"hello"); q=p; printf("%s\n",q); p = realloc(p,1000); printf("%s\n",q); return 0; }

4.7 In the following program we allocate a memory segment of 20 bytes. What will happen to the memory segment after the program terminates?

#include <stdlib.h> #include <string.h> int main() { char *p; p = malloc(20); strcpy(p,"hello"); return 0; }

4.8 Can we use free(p) if previously p was set by a call to realloc() via p = realloc(p,...) ?

4.9 The allocators malloc() , calloc () , and realloc() and the deallocator free() work in a close relationship with the operating system. So how can a program using them be compiled by various compilers and executed on various machines?

4.10 How would you allocate a completely empty memory segment?

Категории