Читаем Linux программирование в примерах полностью

Справочная страница не углубляется в описание проблемы со встроенной alloca() GCC. Если есть переполнение стека, возвращаемое значение является мусором. И у вас нет способа сообщить об этом! Это упущение делает невозможным использование GCC alloca() в устойчивом коде.

Все это должно убедить вас избегать alloca() в любом новом коде, который вы пишете. В любом случае, если приходится писать переносимый код с использованием malloc() и free(), нет причины в использовании также и alloca().

3.2.5. Исследование адресного пространства

Следующая программа, ch03-memaddr.c, подводит итог всему, что мы узнали об адресном пространстве. Она делает множество вещей, которые не следует делать на практике, таких, как вызовы alloca() или непосредственные вызовы brk() и sbrk().

1  /*

2   * ch03-memaddr.с --- Показать адреса секций кода, данных и стека,

3   * а также BSS и динамической памяти.

4   */

5

6  #include

7  #include /* для определения ptrdiff_t в GLIBC */

8  #include

9  #include /* лишь для демонстрации */

10

11 extern void afunc(void); /* функция, показывающая рост стека */

12

13 int bss_var; /* автоматически инициализируется в 0, должна быть в BSS */

14 int data_var = 42; /* инициализируется в не 0, должна быть

15                       в сегменте данных */

16 int

17 main(int argc, char **argv) /* аргументы не используются */

18 {

19  char *p, *b, *nb;

20

21  printf("Text Locations:\n");

22  printf("\tAddress of main: %p\n", main);

23  printf("\tAddress of afunc: %p\n", afunc);

24

25  printf("Stack Locations.\n");

26  afunc();

27

28  p = (char*)alloca(32);

29  if (p != NULL) {

30   printf("\tStart of alloca()'ed array: %p\n", p);

31   printf("\tEnd of alloca()'ed array: %p\n", p + 31);

32  }

33

34  printf("Data Locations:\n");

35  printf("\tAddress of data_var: %p\n", &data_var);

36

37  printf("BSS Locations:\n");

38  printf("\tAddress of bss_var: %p\n", &bss_var);

39

40  b = sbrk((ptrdiff_t)32); /* увеличить адресное пространство */

41  nb = sbrk((ptrdiff_t)0);

42  printf("Heap Locations:\n");

43  printf("\tInitial end of heap: %p\n", b);

44  printf("\tNew end of heap: %p\n", nb);

45

46  b = sbrk((ptrdiff_t)-16); /* сократить его */

47  nb = sbrk((ptrdiff_t)0);

48  printf("\tFinal end of heap: %p\n", nb);

49 }

50

51 void

52 afunc(void)

53 {

54  static int level = 0; /* уровень рекурсии */

55  auto int stack_var; /* автоматическая переменная в стеке */

56

57  if (++level == 3) /* избежать бесконечной рекурсии */

58   return;

59

60  printf("\tStack level %d: address of stack_var: %p\n",

61   level, &stack_var);

62  afunc(); /* рекурсивный вызов */

63 }

Перейти на страницу:

Похожие книги

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных