pixelr pixelr - 1 year ago 73
C++ Question

Simple C++ Program Crash before main is called

I am beginning the coding again but I am stumbling at running this code in FreeBSD 11 release. The code crashes with segmentation fault error.

#include <iostream>

int is_array_sorted(int a[], int n)
if(n==2 || n==1)
return 1;
else if(a[n-1]<a[n-2])
return 0;

int main()
int a[] = {1,2,3,4} ;
int ret = is_array_sorted(a,4);

std::cout<<"sorted ->"<< ret <<std::endl;
return 0;

So, I build this using

c++ file.cpp --std=c++14 -g3

ran and it crashed.

Also, I thought to debug using gdb by setting breakpoint at main symbol. However, it crashes even then giving "Program terminated with signal SIGKILL, Illegal instruction.
The program no longer exists.

Please help out in figuring what am I doing wrong?

Answer Source

Your is_array_sorted function is prototyped to return an int so that is what it must do in all code paths(a).

Yours does so when n is one or two, or when the two elements being examined are out of order, but not when they're in order.

In that case, it drops through to the final statement, and doesn't return an int - that's the most likely cause as to what's crashing the code.

Change that final line to:

return is_array_sorted (a, n-1);

and try again.

As an aside, I'm not really that big a fan of the if ... return else ... school of programming since it unnecessarily complicates the code structure.

You also appear to have an incorrect case in your logic, returning "true" when n is equal to two. Passing the array {5, 4}, with an n of two, should show you why that's a bad idea.

A better approach fixing both those issues, in my opinion, would be something like:

int is_array_sorted (int a[], int n) {
    if (n==1)
        return 1;
    if (a[n-1] < a[n-2])
        return 0;
    return is_array_sorted (a, n-1);

(but, even if you disregard my layout advice, you should still fix the n == 2 issue).

(a) As per C++11 6.6.3 The return statement /2:

Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.