C control flow, memory allocation: Abort trap 6, populate array with characters in string, nested for loops

Viewed 52

This is a question about control flow and possibly memory allocation.

Given a long long number, I am doing the following:

  • converting it into a string
  • iterating through the characters of this string in a prescribed pattern (first layer of for loop)
  • performing an operation on each selected character (second layer of for loop)
  • populating an array with the processed data
#include <stdio.h>
#include <string.h>

int main(void)
{
    long long n = 12345678; // I am given a number

    char str[8]; // initialize string of length 8
    sprintf(str, "%2lld", n); // convert n to string
    printf("The string is: %s\n", str); // check that n is converted to string

    int arr[4]; // initialize array of length 4

    for (int i = 6; i >= 0; i -= 2) // select every other char in string, starting from second-to-last char
        {
            for (int j = 0; j < 4; j++) // select position of array
            {       
                arr[j] = (str[i] - '0') * 2; // convert char to int, multiply by 2, and assign to array position
                printf("The digit is %c and the product is %d\n", str[i], arr[j]); // announce each entry to the array
            }
        }

    for (int k = 0; k < 4; k++) // print contents of array
    {
        printf("The product at position %d is %d\n", k, arr[k]);
    }
    return 0;
}

There are two problems with this code:

  1. Generates Abort trap: 6 error when run on MacOS Terminal.
  2. When the code executes successfully in a practice IDE environment, it generates the following result:

The string is: 12345678
The digit is 7 and the product is 14
The digit is 7 and the product is 14
The digit is 7 and the product is 14
The digit is 7 and the product is 14
The digit is 5 and the product is 10
The digit is 5 and the product is 10
The digit is 5 and the product is 10
The digit is 5 and the product is 10
The digit is 3 and the product is 6
The digit is 3 and the product is 6
The digit is 3 and the product is 6
The digit is 3 and the product is 6
The digit is 1 and the product is 2
The digit is 1 and the product is 2
The digit is 1 and the product is 2
The digit is 1 and the product is 2
The product at position 0 is 2
The product at position 1 is 2
The product at position 2 is 2
The product at position 3 is 2

What I want is to resolve the Abort trap: 6 error and to get the following result:

The string is: 12345678
The digit is 7 and the product is 14
The digit is 5 and the product is 10
The digit is 3 and the product is 6
The digit is 1 and the product is 2
The product at position 0 is 14
The product at position 1 is 10
The product at position 2 is 6
The product at position 3 is 2

What should I change in the code to achieve that?

I have read other posts about Abort trap: 6 and I don't know how this code is committing a mistake in memory allocation/usage.

2 Answers
Related