Thread: Memory access violation

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    7

    Memory access violation

    The following code compiles, but when I try to run case 4 from main() (the search function), my program crashes. Debugging tells me that "An access violation (segmentation fault) raised in" my program. I understand that this is a memory access violation, but I'm not sure why; I've commented most of the parts in the first case of the findEntry() function out, but still get the problem. Any ideas what's causing my memory access problem? Thanks for any and all help.

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <time.h>
    
    /* Prototypes */
    void addEntry(void);
    void delEntry(int);
    void dispBook(int);
    void sortBook(void);
    void findEntry(void);
    void dispEntry(int);
    void delBook(void);
    void capName(int);
    int  random(int);
    
    /*------------*/
    
    /* Globals */
    
    int total=0; //last record available
    
    typedef struct Entry {
            char firstName[20];
            char lastName[20];
            char phoneNum[20];
            } newEntry;
    
            newEntry *bookList;
    
    /*----------*/
            
    int main() { //display menu
        
           int choice; //menu selection
                 
           system("cls");
           printf("\n\n\nPhone Book Application - Menu");
           printf("\n\t1. Add a contact");
           printf("\n\t2. Display contacts");
           printf("\n\t3. Sort contacts");
           printf("\n\t4. Find a contact");
           printf("\n\t5. Choose random contact");
           printf("\n\t6. Delete all contacts");
           printf("\n\t7. Exit");
           
           printf("\n\n Enter a selection: ");
           scanf("%d" , &choice);
           
           switch (choice) {
                  
                  case 1:
                       addEntry();
                       break;
                  case 2:
                       dispBook(total);
                       break;
                  case 3:
                       //sortBook();
                       break;
                  case 4:
                       findEntry();
                       break;
                  case 5:
                       if( total != 0 ) {
                           srand(time(NULL));
                           dispEntry(rand() % total);
                           }
                       else {
                            printf("\n\nNo entries found!\n\n");
                            system("pause");
                            main();
                            }
                       break;
                  case 6:
                       delBook();
                       break;
                  case 7:
                       printf("\n\nGoodbye!\n\n");
                       system("pause");
                       break;
                  default:
                          printf("\n\n\t\tInvalid selection! Try again.");
                          main(); return 0;
                  } //end switch
                  } //end main
                  
    void addEntry() {
         if ( total == 0 ) {
              bookList=(newEntry*) malloc(sizeof(newEntry));
              }
         else {
              bookList=(newEntry*) realloc(bookList,(total+1)*sizeof(newEntry));
              }
    
         system("cls");
         printf("\n\nAdd an entry");
         printf("\n\nEnter first name: ");
         scanf("%s" , bookList[total].firstName);
         printf("\nEnter last name: ");
         scanf("%s" , bookList[total].lastName);
         printf("\nEnter phone number: ");
         scanf("%s" , bookList[total].phoneNum);
         capName(total);
         printf("\n\nRecord added to phone book.\n\n");
         total++;
         system("pause");
         main();
         } //end def
                  
    void delEntry(int entry) {
        int i;
        if ( (total!=(entry+1))) {
        for( i=entry; i<total; i++ ) {
             bookList[i]=bookList[1+i];
             }//end for
             }//end if
             
        free(bookList+total-1); 
        if(total!=0) {
             total--;
             } //end if
        dispBook(total);
        } //end def
    
           
    void dispBook(int total) {
         
         system("cls");
         if ( total != 0 ) {
              if ( total == 1)
              printf("\n\n%d phone book entry:" , total);
              if ( total > 1)
              printf("\n\n%d phone book entries:" , total);
             int i;
             for( i=0; (i+1)<=total; i++ ) {
                  printf("\n\nID: %d" , i+1);
                  printf("\nName: %s %s" , bookList[i].firstName, bookList[i].lastName);
                  printf("\nPhone number: %s" , bookList[i].phoneNum);
                  } //end loop
                  printf("\n\n");
                  
             printf("To delete an entry, enter its ID #,\nor enter 0 to return to the menu.\t");
             int entry; scanf("%d" , &entry);
             
             if (entry == 0)
                { main(); }
             else { 
                  if ( entry>0 && entry <= total)
                  delEntry(entry-1); 
                  else {
                       printf("\n\n\t\tInvalid input! Try again.\n\n"); 
                       system("pause");
                       dispBook(total);
                       }//end else
                       }//end else
                   }//end if
         else {
              printf("\n\nNo entries found!\n\n");
              system("pause");
              main();
              } //end else
              } //end def
              
    /*void sortBook(void) {
         int i;
         newEntry temp;
         for( i=0; i<=total; i++ ) {
              
    }*/
    
    void findEntry(void) {
         system("cls");
         int sChoice;
         char *searchName;
         printf("\nSearch for an entry:");
         printf("\n\t1. by last name");
         printf("\n\t2. by first name");
         printf("\n\n\t3. Back to menu");
         printf("\n\nEnter a selection: ");
         scanf("%d" , &sChoice);
         
         switch(sChoice) {
                         case 1:
                              system("cls");
                              printf("\nEnter last name: ");
                              scanf("%s" , searchName);
                              
                              int u;
                              for ( u=0; u < strlen(searchName); u++ )
                                  searchName[u] = tolower(searchName[u]);
                              
                              int i, x=0;
                              for( i=0; i<total; i++ ) { //I suspect that the problem is in this area
                                   if (strcmp(bookList[i].lastName, searchName) == 1) {
                                      dispEntry(i); 
                                      x++; 
                                      }
                                      }
                              if ( x==0 ) {
                                 printf("No entry found!");}
                                 system("pause");
                                 main();
                              break;
                         case 2:
                              system("cls");
                              printf("\nEnter first name: ");
                              scanf("%s" , searchName);
                              
                              for ( u=0; u <= strlen(searchName); u++ )
                                  searchName[u] = tolower(searchName[u]);
                              
                              for( i=0; i<=total; i++ ) {
                                   if (strcmp(bookList[i].firstName, searchName) == 1) {
                                      dispEntry(i); 
                                      x++; 
                                      }
                                      }
                              if ( x==0 ) {
                                 printf("No entry found!"); }
                                 system("pause");
                                 main(); 
                              break;
                         case 3:
                              main(); break;
                         default:
                                 printf("\n\n\t\tInvalid selection! Try again.");
                                 findEntry();
                         } //end of switch
                         } //end of def
                                                           
                               
    
    void dispEntry(int toDisp) {
         
         system("cls");
              printf("\n\nID: %d" , toDisp+1);
              printf("\nName: %s %s" , bookList[toDisp].firstName, bookList[toDisp].lastName);
              printf("\nPhone number: %s" , bookList[toDisp].phoneNum);
              printf("\n\n");
              
         printf("To delete this entry, enter its ID #,\nor enter 0 to return to the menu.\t");
         int entry; scanf("%d" , &entry);
         
         if (entry == 0)
            { main(); }
         else { 
              if ( entry==toDisp )
              delEntry(entry-1); 
              else {
                   printf("\n\n\t\tInvalid input! Try again.\n\n"); 
                   system("pause");
                   dispBook(total);
                   }//end else
                   }//end else
              } //end def
    
    void delBook(void) {
         int i;
         for( i=0; i<=total; i++ ) {
              free(bookList+i);
              }
         total = 0;
         main();
         }
         
    
    void capName(int change) {
         
         bookList[change].firstName[0]=toupper(bookList[change].firstName[0]);
         bookList[change].lastName[0] =toupper(bookList[change].lastName[0]);
         }

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    You might like to try allocating memory for *searchname.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    You also need to STOP calling main() recursively, and instead put a loop inside main() to repeat all the code you want to repeat.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    Oct 2010
    Posts
    7
    1P: Thank you... I don't know where I got that you could declare a string that way... I could've sworn I'd seen it done that way. Maybe I'm mixing array notation with declaring as a pointer and then initializing recursively...

    Anyway, thanks again.

    2P: I don't want to run the menu recursively (a set number of times). I only return to menu when there's an error or when my individual functions have performed their duties. How else could I display the menu again after one function of it has been performed?

    Thanks for the help, guys.

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Code:
    quit = 0;
    while ( !quit ) {
       displayMenu();
       c = getAnswer();
       switch ( c ) {
          case 1:
            doAction();
            break;
          case 9999:
            quit=1;
            break;
       }
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with custom dynamic memory allocation routines
    By BLauritson in forum C++ Programming
    Replies: 12
    Last Post: 03-11-2010, 07:26 AM
  2. Access Violation error
    By thedoofus in forum C Programming
    Replies: 2
    Last Post: 04-30-2005, 11:33 AM
  3. Access Violation Of Memory Buffer WHY??
    By bartybasher in forum Game Programming
    Replies: 20
    Last Post: 08-13-2004, 07:33 AM
  4. Help! CListCtrl access violation
    By bonkey in forum Windows Programming
    Replies: 4
    Last Post: 11-18-2003, 02:40 PM
  5. Memory Access Error when using Strcpy()
    By fgs3124 in forum C Programming
    Replies: 2
    Last Post: 03-15-2002, 03:07 PM