...
Code Block | ||
---|---|---|
| ||
char *copy(rsize_t n, const char *str) { rsize_t i; char *p; if (n == 0 || n > RSIZE_MAX) { /* Handle unreasonable object size error */ } p = (char *)malloc(n); if (p == NULL) { /* Handle malloc failure */ } for ( i = 0; i < n; ++i ) { p[i] = *str++; } return p; } /* ... */ char str[] = "hi there"; char *p = copy(sizeof(str), str); |
...
Code Block | ||
---|---|---|
| ||
void *alloc(unsigned int blocksize) { return malloc(blocksize); } int read_counted_string(int fd) { unsigned long length; unsigned char *data; if (read_integer_from_network(fd, &length) < 0) { return -1; } data = (unsigned char*) alloc(length); if (data == NULL) { /* Handle mallocerror failure*/ } if (read_network_data(fd, data, length) < 0) { free(data); return -1; } data[length-1] = '\0'; /* ... */ free( data); return 0; } |
...
Code Block | ||
---|---|---|
| ||
void *alloc(rsize_t blocksize) { if (blocksize == 0 || blocksize > RSIZE_MAX) { /* Handle error */ } return malloc(blocksize); } int read_counted_string(int fd) { rsize_t length; unsigned char *data; if (read_integer_from_network(fd, &length) < 0) { return -1; } data = (unsigned char*) alloc(length); if (data == NULL) { /* Handle mallocerror failure*/ } if (read_network_data(fd, data, length) < 0) { free(data); return -1; } data[length-1] = '\0'; /* ... */ free( data); return 0; } |
...