-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuffer.c
More file actions
117 lines (94 loc) · 2.2 KB
/
buffer.c
File metadata and controls
117 lines (94 loc) · 2.2 KB
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
#include <stdio.h>
#include <stdlib.h>
#include "buffer.h"
const int SIZE = 20;
const int INIT_VAL = 0;
struct ring_buffer *ring_buf = NULL;
long init_buffer(void)
{
int i;
// Buffer already exists
if(ring_buf){
printf("Error: Cannot reinitialize a buffer. Exiting...\n");
return -1;
}
ring_buf = malloc(sizeof(ring_buffer_t));
// Allocation error
if (!ring_buf){
printf("Error: Allocation error. Exiting...");
return -1;
}
node_t *node = malloc(sizeof(node_t));
node->data = 0;
node->next = NULL;
ring_buf->read = node;
ring_buf->write = ring_buf->read;
// Start populating all remaining 19 nodes
for (i = 1; i < SIZE; i++){
node_t *new = malloc(sizeof(node_t));
new->data = INIT_VAL;
new->next = NULL;
ring_buf->write->next = new;
ring_buf->write = new;
}
//Make it circular
ring_buf->write->next = ring_buf->read;
ring_buf->length = 0;
return 0;
}
long delete_buffer(void)
{
if(ring_buf){
int i;
// Free individual nodes
for (i = 0; i < SIZE; i++){
node_t *temp = ring_buf->read;
ring_buf->read = ring_buf->read->next;
free(temp);
}
// Free buffer itself
free(ring_buf);
ring_buf = NULL;
return 0;
}
printf("Error: Cannot delete non-existant buffer. Exiting...\n");
return -1;
}
long insert_buffer(int i)
{
int index = 0;
// Buffer doesn't exist or full
if(!ring_buf){
printf("Error: Cannot insert into non-existant buffer. Exiting...\n");
return -1;
}
if(ring_buf->length == SIZE){
printf("Error: Buffer is full - insert failed. Exiting...\n");
return -1;
}
ring_buf->write->data = i;
ring_buf->write = ring_buf->write->next;
++(ring_buf->length);
return 0;
}
long print_buffer(void)
{
if (!ring_buf){
printf("Error: Cannot print non-existant buffer. Exiting...\n");
return -1;
}
int i;
node_t *temp = ring_buf->read;
for (i = 0; i < SIZE; i++){
printf("Address is %p ||| Value is %d\n", temp, temp->data);
temp = temp->next;
}
return 0;
}
int main(void)
{
int insert_int = 300, increment = 50;
init_buffer();
init_buffer(); // Already initialized, shouldn't allow
delete_buffer();
}