Creating Objects
- Syntax:
void * malloc(size_t);
- Creates an object of the requested size.
- Returns a pointer the object. Caller must cast it appropriately.
- Returns NULL if the object could not be created for any reason.
Example
char array[8];
struct {
char ch;
short sh;
long lg;
} foo;
int main() {
char * ch_ptr;
struct foo * foo_ptr;
/* Create a char object */
ch_ptr = (char *)malloc(sizeof(char));
/* Create another char object */
ch_ptr = (char *)malloc(sizeof(array.ch));
/* Create an array object of 4 chars */
ch_ptr = (char *)malloc(sizeof(char) * 4);
/* Create an array object the same size as array */
ch_ptr = (char *)malloc(sizeof(array));
/* Create a struct foo object */
foo_ptr = (struct foo *)malloc(sizeof(foo));
/* Create another struct foo object */
foo_ptr = (struct foo *)malloc(sizeof(struct foo));
}
next slide