Search code examples
cabort

How to get rid of "Abort trap: 6"


Here is my code so far

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv){
    char a[15],d;
    int month, day;
    char *m=&a[15];
    scanf("%s %s", m, &d); 

    if (strncmp(m,"January",7)==0) month = 1;
        else if(strncmp(m,"Febuary", 7)==0) month = 2;
        else if(strncmp(m,"March",5)==0) month = 3;
        else if(strncmp(m,"April",5)==0) month = 4;
        else if(strncmp(m,"May",3)==0) month = 5;
        else if(strncmp(m,"June",4)==0) month = 6;
        else if(strncmp(m,"July",4)==0) month = 7;
        else if(strncmp(m,"August",6)==0) month = 8;
        else if(strncmp(m,"September",9)==0) month = 9;
        else if(strncmp(m,"October",7)==0) month = 10;
        else if(strncmp(m,"November",8)==0) month = 11;
        else if(strncmp(m,"December",8)==0) month = 12;
        else {month =0; printf("invalid date");};

    day = atoi(&d);

    int months[] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
    int days = months[month-1] + day;
    printf("%s %d is the %d day of the year\n",m, day, days);

    return 0;
}

All of the code runs correctly but then at the end of the program it gives me the error message Abort trap:6. I know this has to do with memory allocation, but I don't know what specifically is causing it.

Edit: Side note, for this code I can assume that the date will be typed in a correct format, e.g "Month Day" with the month always being a capital letter and an actual month, etc.


Solution

  • The abort trap occurs because d is a single character, but you attempt to store a string into it. scanf is able to read and convert numbers, so you could eliminate d and the atoi and just use scanf to read the day directly.

    I should also point out that the line

    char *m=&a[15];
    

    points m to the end of the array. If you eliminate a and declare m as the array, then m can be used as a pointer to the beginning of the array.

    The first few lines of your code should look like this

    int main(int argc, char **argv){
        char m[16];
        int month, day;
        scanf("%15s%d", m, &day); 
    
        if (strcmp(m,"January")==0) month = 1;
    

    Side note: using strncmp is unnecessary (since both m and the constant string are well formed) and error prone (since you could get the length wrong). So the compares should be done with strcmp.

    And as @JonathanLeffler pointed out in the comment, using strncmp would allow invalid month names to pass the comparison. For example,

    strncmp( "Maybe", "May", 3 )
    

    will return 0.