error message: abort() has been called

I have wrote a small function that swaps array elements and count the number of swaps.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
int swap(string array[], int n) {
	

	int first = 0;
	int last = n-1;
	int numSwap = 0;

	if (n == 0) numSwap = 0;
	else {
		while (first != last) {
			string temp;
			temp = array[first];
			array[first] = array[last];
			array[last] = temp;

			first++;
			last--;
			numSwap++;
		}
	}

	return numSwap;
}

int main()
{
	string h[11] = { "a","b","c","1","2","3","d","e","f","f","2" };
	 
	assert(swap(h, 10) == 5);

	cout << "all tests succeeded" << endl;
}



this assert(swap(h,10) ==5); should be correct but the program gives me an error message "abort() has been called"

other asserts:
1
2
3
4
	assert(swap(h, 11) == 5);
	assert(swap(h, 3) == 1);
	assert(swap(h, 1) == 0);
	assert(swap(h, 0) == 0);


work fine and shows "all tests succeeded" message
what does this error message mean??
Last edited on
Same Issue..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <string>
#include "assert.h"

using namespace std;

int flipAround(string array[], int n) 
{
	int first = 0;
	int last = n-1;
	int numSwap = 0;

	if (n == 0) numSwap = 0;
	else 
	{
		while (first != last) 
		{
			string temp;
			temp = array[first];
			array[first] = array[last];
			array[last] = temp;

			first++;
			last--;
			numSwap++;
		}
	}
	return numSwap;
}

int main()
{
	string h[11] = { "samwell","jon","howard", "ucla", "margaery","daenerys", "tyrion", "daenerys", "ucla", "howard" ,"apple" };
	assert(flipAround(h, 10) == 5);
	cout << "all tests succeeded" << endl;
	
	getchar();
	return 0;
}
Last edited on
Your program exhibits UB because for an array with an even, nonzero number of elements, first will never equal last -- first and last "pass" each-other.

Change line 10 to
while (first < last)
@mbozzi that makes so much sense! thank you :)
Topic archived. No new replies allowed.