Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // $Id: $
- #include <assert.h>
- #include <libgen.h>
- #include <stdio.h>
- #include <stdlib.h>
- //typeduf enum { FALSE = 0, TRUE = 1} bool;
- typedef struct node *node_ref;
- struct node {
- double item;
- node_ref link;
- };
- void insert(node_ref *head, double number ) {
- node_ref curr = *head;;
- node_ref prev = NULL;
- while(curr != NULL) {
- if (curr->item < number) break;
- prev = curr;
- curr = curr->link;
- }
- node_ref tmp = malloc(sizeof(struct node));
- assert (tmp != NULL);
- tmp->item = number;
- // assert (tmp->item != NULL);
- tmp->link = curr;
- if(prev==NULL) *head = tmp;
- else prev->link =tmp;
- }
- int main (int argc, char **argv) {
- char *progname = basename (argv[0]);
- char err_buffer [256];
- char err_buf_fmt[16];
- sprintf (err_buf_fmt, "%%%lds", sizeof err_buffer - 1);
- printf ("err_buf_fmt = \"%s\"\n", err_buf_fmt);
- node_ref head =NULL;
- for (;;) {
- // Try to read a double number. Print an error message if a
- // word is not recognized as a number. Stop at end of file.
- double number;
- int scancount = scanf ("%lg", &number);
- if (scancount == EOF) {
- printf ("%s: EOF\n", progname);
- break;
- }else if (scancount == 1) {
- insert(&head, number);
- }else {
- scancount = scanf (err_buf_fmt, err_buffer);
- assert (scancount == 1);
- printf ("%s: bad number \"%s\"\n", progname, err_buffer);
- };
- };
- // return EXIT_SUCCESS;
- // int max = argc < 2 ? 10 : atoi (argv[1]);
- // printf ("%s: looping %d times\n", progname, max);
- /* for (int count = 0; count < max; ++count) {
- node_ref new = malloc (sizeof (struct node));
- assert (new != NULL);
- new->item = drand48() * 1e6;
- new->link = head;
- head = new;
- }*/
- //
- // Loop down the list, printing out each entry in debug mode.
- //
- printf ("&head= %p\n", (void*) &head);
- printf ("head= %p\n", (void*) head);
- for (node_ref curr = head; curr != NULL; curr = curr->link) {
- printf ("%p -> struct node {item= %.15g, link= %p}\n",
- (void*) curr, curr->item, (void*) curr->link);
- }
- printf ("NULL= %p\n", (void*) NULL);
- //
- // Free up all of the nodes.
- //
- while (head != NULL) {
- node_ref old = head;
- head = head->link;
- free (old);
- }
- //
- // Deliberately cause some memory leaks and throw away result.
- //
- for (int leaks = 0; leaks < 4; ++leaks) malloc (256);
- malloc (4096);
- return EXIT_SUCCESS;
- }
- /*
- //TEST// valgrind --leak-check=full --log-file=numlist.lisval \
- //TEST//./numlist >numlist.lisout 2>&1
- //TEST// mkpspdf numlist.ps numlist.c* numlist.lis*
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement