简体   繁体   中英

How to resolve: Caught unexpected signal: SIGSEGV (11). Invalid memory access

A kyu on codewars asks for the following:

Complete the method which accepts an array of integers, and returns one of the following:

"yes, ascending" - if the numbers in the array are sorted in an ascending order "yes, descending" - if the numbers in the array are sorted in a descending order "no" - otherwise You can assume the array will always be valid, and there will always be one correct answer.

I put together the following but run into "Caught unexpected signal: SIGSEGV (11). Invalid memory access" when testing. Can someone please explain the error to me and what part of the script triggers it?

#include <stdio.h>

char* isSortedAndHow(int* array, int arrayLength)
{
  // Create an empty array where ascending or descending test results will be stored
  int results[] = {};
  int i;
    // If the value is greater than the previous one add a 1, if smaller add a 0, if equal, add 1000
    for (i = 1; array[i]; i++){
      if (array[i] < array[i-1]){
        results[i-1] = 0;
      } else if (array[i] > array[i-1]) {
          results[i-1] = 1;
      } else {
          results[i-1] = 1000;
      }
    }
  // Add the value of all values in the results array and return the answer
  int sum = 0;
  for (i=0; results[i]; i++) {
    sum = sum + results[i];
  } if (sum == 0) {
     return "yes, descending";
  } else if (sum == (arrayLength - 1)) {
     return "yes, ascending";
  } else {
       return "no";
  }
}

The culprit is the line

    int results[] = {};

You declare an array of int with a size of zero. Further down the code you try to write into that array: BOOM!

One possible solution is to allocate the array with the size arrayLength . But as commenters said, you don't need this array at all. Rethink your algorithm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM