Thread: Mysterious Crash

  1. #1
    Registered User
    Join Date
    May 2013
    Posts
    11

    Mysterious Crash

    So I am doing a problem from C How To Program 7th Edition by Deitel. The problem is 8.10 for those who might have access to the book.

    In a nutshell, I am comparing strings up to n characters. The program funs fine however at the end it crashes. I cannot figure out why

    Code:
    #include <string.h>
    #include <stdio.h>
    
    int main(void){
    
        char *string1, *string2;
    
        int n, compare;
    
        puts("Enter a string");
        fgets(string1,20, stdin);
    
        puts("Enter a string");
        fgets(string2,20, stdin);
    
        puts("Enter the amount of characters to compare");
        scanf("%d",&n);
    
        compare = strncmp(string1, string2, n);
    
        if(compare == 0)
            printf("Strings compares are equal\n");
        else
            printf("string 1 is %s String 2\n", (compare > 0) ? "greater than" : "less than");
    
        printf("Ending ....\n");
    
        return 0;
    }

  2. #2
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    You NEED to allocate space for the C-string!!
    Your pointers are pointer to random locations; of course it crashes sometimes.

    This code creates to pointers that point to a random location; likely to a location that you do not own or a location you do own that gets over written.
    Code:
    char *string1, *string2;
    Simple fix is this line instead
    Code:
    char string1[20+1], string2[20+1];
    Tim S.
    Last edited by stahta01; 05-26-2013 at 05:02 PM.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  3. #3
    Registered User
    Join Date
    May 2013
    Posts
    11
    Thank You. You are right, it does crash SOMETIMES.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. mysterious seg fault!
    By MK27 in forum C++ Programming
    Replies: 12
    Last Post: 03-12-2010, 02:29 AM
  2. Mysterious Seg Fault
    By Akalic in forum C Programming
    Replies: 6
    Last Post: 10-26-2009, 04:16 PM
  3. mysterious code.......(??)
    By deltabird in forum C Programming
    Replies: 7
    Last Post: 04-11-2003, 03:58 PM
  4. Mysterious crash on DestroyWindow()
    By Hunter2 in forum Game Programming
    Replies: 8
    Last Post: 02-03-2003, 08:03 PM
  5. Mysterious message from vVv
    By sean in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 06-08-2002, 04:11 PM