Graphics Programs Reference
In-Depth Information
printf("char_ptr (%p) --> '%s'\n", char_ptr, char_ptr);
printf("\t[-] freeing int_ptr's heap memory...\n");
free(int_ptr); // Freeing heap memory
printf("\t[-] freeing char_ptr's heap memory...\n");
free(char_ptr); // Freeing the other block of heap memory
}
void *errorchecked_malloc(unsigned int size) { // An error-checked malloc() function
void *ptr;
ptr = malloc(size);
if(ptr == NULL) {
fprintf(stderr, "Error: could not allocate heap memory.\n");
exit(-1);
}
return ptr;
}
The errorchecked_heap.c program is basically equivalent to the
previous heap_example.c code, except the heap memory allocation and
error checking has been gathered into a single function. The first line of code
[ void *errorchecked_malloc(unsigned int); ] is the function prototype. This lets
the compiler know that there will be a function called errorchecked_malloc() that
expects a single, unsigned integer argument and returns a void pointer. The
actual function can then be anywhere; in this case it is after the main() func-
tion. The function itself is quite simple; it just accepts the size in bytes to
allocate and attempts to allocate that much memory using malloc() . If the
allocation fails, the error-checking code displays an error and the program
exits; otherwise, it returns the pointer to the newly allocated heap memory.
This way, the custom errorchecked_malloc() function can be used in place of
anormal malloc() , eliminating the need for repetitious error checking after-
ward. This should begin to highlight the usefulness of programming with
functions.
0x280
Building on Basics
Once you understand the basic concepts of C programming, the rest is pretty
easy. The bulk of the power of C comes from using other functions. In fact,
if the functions were removed from any of the preceding programs, all that
would remain are very basic statements.
0x281
File Access
There are two primary ways to access files in C: file descriptors and file-
streams. File descriptors use a set of low-level I/O functions, and filestreams are
a higher-level form of buffered I/O that is built on the lower-level functions.
Some consider the filestream functions easier to program with; however, file
descriptors are more direct. In this topic, the focus will be on the low-level
I/O functions that use file descriptors.
Search WWH ::




Custom Search