Skip to content

Commit 4c7f300

Browse files
committed
improve knr_malloc error check and use stddef.h for NULL
1 parent ff6e853 commit 4c7f300

File tree

3 files changed

+16
-17
lines changed

3 files changed

+16
-17
lines changed

chapter08/8-6.c

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
* By Faisal Saadatmand
66
*/
77

8-
#define NULL 0
8+
#include <stddef.h> /* for NULL */
9+
910
#define NALLOC 1024 /* minimum #units to request */
1011

1112
typedef long Align; /* for alignment to long boundary */

chapter08/8-7.c

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,10 @@
66
* By Faisal Saadatmand
77
*/
88

9-
#define NULL 0
10-
#define NALLOC 1024 /* minimum #units to request */
11-
#define MAXBYTES 1048576 /* 1 Megabytes */
9+
#include <stddef.h> /* for NULL */
10+
#include <limits.h> /* for INT_MAX */
11+
12+
#define NALLOC 1024 /* minimum #units to request */
1213

1314
typedef long Align; /* for alignment to long boundary */
1415

@@ -36,7 +37,7 @@ void *knr_malloc(unsigned nbytes)
3637
Header *prevp; /* pointer to previous block */
3738
unsigned nunits;
3839

39-
if (nbytes > MAXBYTES) /* error check */
40+
if (nbytes == 0 || nbytes > INT_MAX) /* error check */
4041
return NULL;
4142

4243
/* round up to allocate in units of sizeof(Header) */
@@ -132,19 +133,15 @@ void knr_free(void *ap)
132133

133134
#include <stdio.h>
134135

135-
#define SIZE 21 /* chenge to test error checking */
136+
#define SIZE 21 /* chenge value to test error checking */
136137

137138
int main(void)
138139
{
139-
int i;
140140
char *s;
141141

142-
if ((s = (char *) knr_malloc(SIZE * sizeof(char))) != NULL) {
143-
for (i = 0; i < SIZE - 1; i++)
144-
s[i] = i + '0';
145-
s[i] = '\0';
146-
printf("%s\n", s);
147-
} else
142+
if ((s = (char *) knr_malloc(SIZE * sizeof(char))) != NULL)
143+
printf("Valid size\n");
144+
else
148145
fprintf(stderr, "Invalid size\n");
149146

150147
knr_free(s);

chapter08/8-8.c

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,10 @@
66
* By Faisal Saadatmand
77
*/
88

9-
#define NULL 0
10-
#define NALLOC 1024 /* minimum #units to request */
11-
#define MAXBYTES 1048576 /* 1 Megabytes */
9+
#include <stddef.h> /* for NULL */
10+
#include <limits.h> /* for INT_MAX */
11+
12+
#define NALLOC 1024 /* minimum #units to request */
1213

1314
typedef long Align; /* for alignment to long boundary */
1415

@@ -36,7 +37,7 @@ void *knr_malloc(unsigned nbytes)
3637
Header *prevp; /* pointer to previous block */
3738
unsigned nunits;
3839

39-
if (nbytes > MAXBYTES) /* error check */
40+
if (nbytes == 0 || nbytes > INT_MAX) /* error check */
4041
return NULL;
4142

4243
/* round up to allocate in units of sizeof(Header) */

0 commit comments

Comments
 (0)