0 / 0 / 0
Регистрация: 19.03.2018
Сообщений: 11
1

Почему так себя ведёт программа? Функции: malloc(), realloc(), free()

05.04.2018, 17:30. Показов 1621. Ответов 1
Метки нет (Все метки)

Почему большинство значений в output 0 и несколько из значений не равно 0?

C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
/*
 * malloc_play.c: bizzarro programma per studiare il comportamento delle system call
 *                malloc(), realloc() e free().
 *
 * versione 1.5 del 22/03/2018
 *
 * Programma sviluppato a supporto del laboratorio di
 * Sistemi di Elaborazione dell'Informazione del corso di laurea
 * in Informatica classe L-31 presso l'Universita` degli Studi di
 * Genova, anno accademico 2017/2018.
 *
 * Copyright (C) 2013-2018 by Giovanni Chiola <chiolag@acm.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 */
 
#include<stdlib.h>
#include<stdio.h>
 
/*** Just playing with the malloc(), realloc(), free()
 *** system calls in order to guess how memory management
 *** is implemented on this machine. If you get SEGMENTATION
 *** FAULT while addressing unallocated heap memory, just run
 *** the program with different "min" and/or "max" values,
 *** explicitly given on the command line through argv[]
 *** NOTICE: the default values are appropriate for the 32bit systems
 *** available in the labs ***/
int main(int argc, char**argv){
    unsigned char *p, *q, *oldp;
    int sz=1, min=-8, max=60;
 
    if ( argc > 1 )
        sscanf(argv[1],"%d",&sz);
    if ( sz <= 0 )
        sz = 1;
    else if ( sz > 300 )
        sz = 300;
    if ( argc > 2 )
        sscanf(argv[2],"%d",&min);
    if ( min > -1 )
        min = -1;
    else if ( min < -50 )
        min = -50;
    if ( argc > 3 )
        sscanf(argv[3],"%d",&max);
    if ( max < sz )
        max = sz;
    else if ( max > (sz+100) )
        max = sz+100;
    printf("... allocating %d unsigned chars, min=%d, max=%d\n\n",sz,min,max);
    p = (unsigned char*)malloc(sz);
    if ( p == NULL ) {
        printf("could not allocate p\n");
        exit(0);
      }
    printf("*p=%hhu\n",*p);
    { int i;
      for ( i = -1 ; i >= min ; i-- )
        printf("p[%d]=%hhu\n",i,p[i]);
      for ( i = 1 ; i <= max ; i++ )
        printf("p[%d]=%hhu\n",i,p[i]);
    }
    printf("\n... allocating %d more unsigned chars to a different pointer\n\n",sz);
    q = (unsigned char*)malloc(sz);
    if ( q == NULL ) {
        printf("could not allocate q\n");
        exit(0);
      }
    { int i;
      for ( i = -1 ; i >= min ; i-- )
        printf("q[%d]=%hhu\n",i,q[i]);
      for ( i = 0 ; i <= max ; i++ )
        printf("q[%d]=%hhu\n",i,q[i]);
    }
    { int i;
      for ( i = -1 ; i >= min ; i-- )
        printf("p[%d]=%hhu\n",i,p[i]);
      for ( i = 0 ; i <= max ; i++ )
        printf("p[%d]=%hhu\n",i,p[i]);
    }
    sz += 10;
    printf("\n... reallocating %d unsigned chars\n\n",sz);
    oldp = p;
    p = (unsigned char*)realloc((void*)p,sz);
    { int i;
      for ( i = -1 ; i >= min ; i-- )
        printf("p[%d]=%hhu\n",i,p[i]);
      for ( i = 0 ; i <= max ; i++ )
        printf("p[%d]=%hhu\n",i,p[i]);
      for ( i = -1 ; i >= min ; i-- )
        printf("oldp[%d]=%hhu\n",i,oldp[i]);
      for ( i = 0 ; i <= max ; i++ )
        printf("oldp[%d]=%hhu\n",i,oldp[i]);
    }
    sz += 15;
    printf("\n... reallocating %d unsigned chars\n\n",sz);
    p = (unsigned char*)realloc((void*)p,sz);
    { int i;
      for ( i = -1 ; i >= min ; i-- )
        printf("p[%d]=%hhu\n",i,p[i]);
      for ( i = 0 ; i <= max ; i++ )
        printf("p[%d]=%hhu\n",i,p[i]);
      for ( i = -1 ; i >= min ; i-- )
        printf("oldp[%d]=%hhu\n",i,oldp[i]);
      for ( i = 0 ; i <= max ; i++ )
        printf("oldp[%d]=%hhu\n",i,oldp[i]);
    }
    sz -= 25;
    printf("\n... reallocating %d unsigned chars\n\n",sz);
    p = (unsigned char*)realloc((void*)p,sz);
    { int i;
      for ( i = -1 ; i >= min ; i-- )
        printf("p[%d]=%hhu\n",i,p[i]);
      for ( i = 0 ; i <= max ; i++ )
        printf("p[%d]=%hhu\n",i,p[i]);
      for ( i = -1 ; i >= min ; i-- )
        printf("oldp[%d]=%hhu\n",i,oldp[i]);
      for ( i = 0 ; i <= max ; i++ )
        printf("oldp[%d]=%hhu\n",i,oldp[i]);
    }
    printf("\n... freeing p\n\n",sz);
    free((void*)p);
    { int i;
      for ( i = 0 ; i >= min ; i-- )
        printf("p[%d]=%hhu\n",i,p[i]);
    }
    printf("\n... freeing q\n\n",sz);
    free((void*)q);
    { int i;
      for ( i = 0 ; i >= min ; i-- )
        printf("q[%d]=%hhu\n",i,q[i]);
      for ( i = -1 ; i >= min ; i-- )
        printf("oldp[%d]=%hhu\n",i,oldp[i]);
      for ( i = 0 ; i <= max ; i++ )
        printf("oldp[%d]=%hhu\n",i,oldp[i]);
    }
    printf("\n... freeing oldp\n\n",sz);
    free((void*)oldp);
    { int i;
      for ( i = -1 ; i >= min ; i-- )
        printf("oldp[%d]=%hhu\n",i,oldp[i]);
      for ( i = 0 ; i <= max ; i++ )
        printf("oldp[%d]=%hhu\n",i,oldp[i]);
    }
    exit(0);
}
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
05.04.2018, 17:30
Ответы с готовыми решениями:

Непонятно почему ведёт себя так программа
Задачка: //На шахматной доске 8х8 расположены три фигуры: ферзь, ладья и конь. //Требуется...

Нюансы работы с массивами: почему программа ведёт себя не так, как ожидается?
// ConsoleApplication20.cpp: определяет точку входа для консольного приложения. // #include...

Нюансы работы с оператором ветвления if else: почему программа ведёт себя не так, как ожидается?
#include &lt;iostream&gt; #include &lt;string&gt; using namespace std; void check_weekday(string day) { if...

Нюансы работы с оператором ветвления if else: почему программа ведёт себя не так, как ожидается?
Имеется код: int a; char q; for (;;) { cout &lt;&lt; &quot;Введите число: &quot;; cin &gt;&gt; a;

1
6044 / 2159 / 753
Регистрация: 10.12.2010
Сообщений: 6,007
Записей в блоге: 3
06.04.2018, 10:25 2
Ну потому что в памяти в плане значений по выделенным адресам полный рандом. Как и должно быть. malloc/realloc не делают никаких видов инициализации выделяемой памяти.
0
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
06.04.2018, 10:25
Помогаю со студенческими работами здесь

В чем преимущества new и delete и могут ли они действительно заменить функции calloc, malloc, free, realloc?
Язык программирования C поддерживает функции динамического управления пямятью: calloc, malloc,...

Почему IE так себя ведет?
У меня сайт на движке wordpress в браузерах Opera и Mozilla все работает отлично, а вот в IE сам...

Работа с памятью через malloc,realloc и free
Вот начал работать с памятью в c++ и появилось несколько вопросов. 1 - r = (int...

Почему DHCP ведет себя так?
Добрый день, В здании несколько организаций, но Интернет общий, настроил Mikrotik RB951G-2HnD...

Инкремент в цикле. Почему себя так ведет?
Есть функция, выполняющая запросы в БД. Она должна возвращать ответ в массиве. Все строки. ...

Есть блок с positioin:fixed; почему он так странно себя ведет?
Разметка: &lt;div class=&quot;one&quot;&gt; &lt;div class=&quot;two&quot;&gt;&lt;/div&gt; &lt;/div&gt; Стили:


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2023, CyberForum.ru