Segmentation fault error 11 C++ - c++

So I'm getting a segmentation fault error in the beginning of the code. I've tried running some tests at the different points and the error seems to be when i allocate memory for the array. Ive just started learning about heap and stack memory so I'm not really sure if I'm doing something wrong there. Any help would be appreciated.
#include <iostream>
using namespace std;
//Function Prototypes
void sort(int A[], int n);
int findMin(int A[], int n, int j);
int swap(int& a, int& b);
double median(int A[], int n);
void output1(int median);
void output2(double median);
int main()
{
int size;
int array[size]; //Segmentaion fault here
int i = 0;
cout << "Enter the size of the list (< 1 to quit): ";
cin >> size;
while(size >= 1)
{
double element;
cout << "Enter element " << i+1 << ": ";
cin >> element;
array[i] = element;
i++;
while(i < size)
{
cout << "Enter element " << i+1 << ": ";
cin >> element;
array[i] = element;
i++;
}
sort(array, size);
median(array, size);
cout << "Enter the size of the list (< 1 to quit): ";
cin >> size;
}
delete [] array;
return 0;
}
void sort(int A[], int n)
{
int min;
for(int i = 0; i < n; i++)
{
min = findMin(A,n,i);
//min = findMinIndex(p, size, i);
//if(min )
swap(A[i],A[min]);
//swap(p[i],p[min]);
}
}
int findMin(int A[], int n, int j)
{
int minIndex = j;
for(int i = j+1; i < n; i++)
if(A[i]<A[minIndex])
minIndex = i;
return minIndex;
}
int swap(int& a, int& b)
{
int temp;
temp = a;
a = b;
b = temp;
}
void output1(int median)
{
cout << "The median is " << median << "." << endl;
}
void output2(double median)
{
cout << "The median is " << median << "." << endl;
}
double median(int A[], int n)
{
if(n % 2 == 0)
{
int div1 = n / 2;
int num1 = A[div1];
int num2 = A[div1 -1];
double median = (num1 + num2) / 2;
output2(median);
}
else
{
int div2 = n - 1;
int median = div2 / 2;
output1(median);
}
}

Because you are not initialising size, the value in that variable could literally be anything. If it happens to be excessively large, say 106,840,406, then you won't be able to get an int[] of that size.
So basically, initialise your size variable to something sensible.

Segmentation Fault 11 equals to say "Index out of range"...
Index
0, 1, 2, 3, 4 ,5
Value 5, 6 ,1 ,9 ,8 ,7
Array length is 6, but its last index is 5.. for example, if we control a for cycle with 6 then we got Segmentation Fault 11...

An array in c++ has to be initialized at the with a fixed size. In your case, size is not initialized to any fixed integer value, which is illegal in c++ and will cause the compiler to produce an error message.
If you try the following line just before you initialize the array of size size, you can tell what the size originally is:
cout << size << endl;
I compiled your code with this line and got this int size before the compiler failed:
1995231824 (This differs for every compiler and computer, but every number will be as big and useless as this one)
Trying to have such a big array will naturally lead to a segmentation fault. That's why you would have to initialize the variable size to a fixed number. This will eliminate the segmentation fault.

Related

Find the largest index of the largest element in an array (C++)

I have an array generated with random integers from 0 to 9, I have a function that does that. I also have a function that determines what the largest element from the array is. I need to write another function that determine the index of the largest variable. I believe the problem is that I cannot call the function within the function but it could be something else.
The code I have is below:
#include <iostream>
#include <ctime>
#include <time.h>
using namespace std;
void initialize(int arr[], int size);
void print(int arr[], int size);
void findLargest(int arr[], int size);
void largestIndex(int arr[], int size);
int main(){
const int SIZE = 10;
int myList[SIZE];
initialize(myList, SIZE);
print(myList, SIZE);
findLargest(myList, SIZE);
largestIndex(myList, SIZE);
return 0;
}
void initialize(int arr[], int size){
srand(time(0));
for(int i = 0; i < size; i++){
arr[i] = (rand() % 10);
}
}
void print(int arr[], int size){
for(int j = 0; j < size; j++){
cout<<arr[j]<< endl;
}
}
void findLargest(int arr[], int size){
for(int i = 0; i < size; i++){
if(arr[0] < arr[i])
arr[0] = arr[i];
}
cout << "The largest element in the array is " << arr[0]<< endl;;
}
void largestIndex(int arr[], int size){
for(int i = 0; i < size; i++){
if(arr[i] == 9){
cout<< "The index of the largest element is " + i <<endl;
}
}
}
Ran it through compiler explorer
https://godbolt.org/z/c9ETjaq3z
Revealing this error message
<source>:69:59: warning: adding 'int' to a string does not append to the string [-Wstring-plus-int]
cout<< "The index of the largest element is " + i <<endl;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~
<source>:69:59: note: use array indexing to silence this warning
cout<< "The index of the largest element is " + i <<endl;
^
& [ ]
This line
cout << "The index of the largest element is " + i <<endl;
Adds i to the pointer to the character string "The index of the largest element is ". The result is that you carve of the beginning of the string instead of showing the value of i.
What you want is
cout << "The index of the largest element is " << i <<endl;
or
cout << "The index of the largest element is " + std::to_string(i) <<endl;
You might want to consider using std::max_element
auto largest = *std::max_element(arr, arr + size);
std::cout << "Largest... = " << largest << std::endl;

how to use user input array in heap sorting

I'm a beginner so please excuse me if it is a dumb question.
I am trying to code a heap sort that takes input from user in an array and heap sorts it but i can not find a way to implement user input array in my code.
at the end, in the main function, i have to use array arr[]={} but i either have to define the elements or the number of elements so it creates zeros if i define the array as arr[10]={}
here is the code :
// Heap Sort in C++
#include <iostream>
using namespace std;
void heapify(int arr[], int n, int i) {
// Find largest among root, left child and right child
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] > arr[largest])
largest = left;
if (right < n && arr[right] > arr[largest])
largest = right;
// Swap and continue heapifying if root is not largest
if (largest != i) {
swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}
// main function to do heap sort
void heapSort(int arr[], int n) {
// Build max heap
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// Heap sort
for (int i = n - 1; i >= 0; i--) {
swap(arr[0], arr[i]);
// Heapify root element to get highest element at root again
heapify(arr, i, 0);
}
}
// Print an array
void printArray(int arr[], int n) {
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
cout << "\n";
}
// Driver code
int main() {
int arr[10] = { };
cout << "Enter the numbers : " << endl;
for (int x = 1; x <= 5; x++)
{
cin >> arr[x];
}
int n = sizeof(arr) / sizeof(arr[0]);
heapSort(arr, n);
cout << "Sorted array is \n";
printArray(arr, n);
}
here is the output :
code output image
You can consider std::vector and pass it by reference to your heapify(...) to save memory.

Getting a weird negative number in my output when using an array I modified in one function, in another function

I am writing a program that takes a user-inputted list of up to 25 integers, then prints the sorted list using bubble sorting, the sorted list in descending order, and some other info about the list like the median, minimum and maximum, and mode.
I have tested all of my functions within the program individually on an array I created using initializer lists (not from user input/cin) and they work fine, but when I run the program something is off. For example, when I input 1,2,3,4, the function that prints the sorted list in descending order prints 3,2,1, -858993460. It always leaves out the greatest integer and adds on -858993460 at the end no matter what values I put into the input array. Here's the relevant part of my code:
#include <iostream>
using namespace std;
void input(int ulist[26], int& n);
void Bubblesort(int ulist[26], int slist[26], int n);
void print(int list[26], int n);
int n;
void reversesort(int slist[26], int n);
void main()
{
int ulist[26], slist[26];
input(ulist, n);
cout << "Unsorted";
print(ulist, n);
cout << "Sorted";
Bubblesort(ulist, slist, n);
print(slist, n);
reversesort(slist, n);
cin >> n;
}
void input(int ulist[26], int& n)
{
int i(0), value;
cout << "enter value : \n";
cin >> value;
while (i < 25 && value != -999)
{
ulist[i] = value;
i++;
if (i < 25)
{
cin >> value;
}
}
n = i;
}
void Bubblesort(int ulist[26], int slist[26], int n)
{
int i, j, temp;
for (i = 0; i < n; i++)
slist[i] = ulist[i];
for (j = 25 - 1; j > 0; j--) //25 is Length of the array
for (i = 0; i < j; i++)
if (slist[i] > slist[i + 1])
{
temp = slist[i];
slist[i] = slist[i + 1];
slist[i + 1] = temp;
}
}
void print(int list[26], int n)
{
int i;
cout << " list of numbers are : \n";
for (i = 0; i < n; ++i)
{
cout << list[i] << '\n';
}
cout << "\n\n";
}
void reversesort(int slist[26], int n) //checked w online compiler, works
{
cout << "List of numbers in descending order is: \n";
for (int i = n - 1; i >= 0; --i)
cout << slist[i] << ", ";
cout << "\n";
}
I'm assuming this is some sort of memory problem and that the source of this has to do with passing slist, which was modified in the bubblesort function, through the functions I wrote. I'm pretty new to C++ (coming from python) so I'm assuming I'm missing something as far as passing arrays to functions is concerned.
EDIT: I guess to sum everything up - how can I take the data inputted in the input function and use that array in another function? And how can I take the array that has been sorted by the bubblesort function and use that array in another function?
The first instance of undefined behavior in your code is
if (slist[i] > slist[i + 1])
in Bubblesort.
Due to
for (j = 25 - 1; j > 0; j--)
for (i = 0; i < j; i++)
the maximum index accessed by this loop is slist[24] (24 from i + 1 where i < j and j = 25 - 1 = 24, so i = 23).
Your input is only 4 numbers, so only slist[0] through slist[3] are initialized. The remaining elements (slist[4] through slist[25]) are uninitialized. Reading from an uninitialized variable has undefined behavior.

Find the index of the minimum element in a subarray

The function FindSubArrayMinimum is suppose to return the index of the minimum value in an array between the values (left,right). Instead of returning 1 as it should, it returns 7.
Here is my code:
#include <iostream>
using namespace std;
class Minimum {
int *array;
int arrayLen;
public:
Minimum(int *array, int arrayLen) {
}
void swap(int &a, int &b) {
int x;
x = a;
a = b;
b = x;
}
int findMinimum(int a, int b) {
if(a < b){
return a;
}else{
return b;
}
}
int findArrayMinimum(int a[], int arraySize) {
int min=a[0];
for(int i=0;i<arraySize-1;i++){
if(a[i] < min){
min = i;
}
}
return min;
}
int findSubArrayMinimum(int a[], int arraySize, int left, int right) {
int min = a[left];
for(int i=left;i<right+1;i++){
if(a[i] < min){
cout << min << endl;
min = i;
}
}
return min;
}
int findSubArrayMinimumAndSwap(int left, int right, int swapIndex) {
}
};
int main() {
int A[5] = {47, 7, 21, -1, 11};
Minimum min(A, 5);
cout << "Minimum of 7 and 11 is " << min.findMinimum(7, 11) << endl;
int x = 5, y = 7;
min.swap(x, y);
cout << "x = " << x << ", y = " << y << endl;
cout << "Minimum value is at position " << min.findArrayMinimum(A,5) << endl;
cout << "Minimum value between [1,2] is at position " <<
min.findSubArrayMinimum(A,5,1,2)<< endl;
return 0;
}
I cannot for the life of me figure out why it won't return the minimum index. Logically speaking it should work unless I'm missing something?
all of my other functions as all the ones I have finished I have working.
It is not true. In findArrayMinimum the loop should be
for(int i=0;i<arraySize;i++)
Or
for(int i=0;i<=arraySize-1;i++)
The initial value an the condition in the loop are also wrong. Should be int min=0 and if(a[i] < a[min])
Instead of returning 1 as it should, it returns 7.
findSubArrayMinimum is nice, except initial minimum value int min = a[left], should be int min = left and the condition in the loop should be if(a[i] < a[min]).
arraySize is odd in findSubArrayMinimum, it is not used.
Your do not need the separate implementation for findSubArray. You can do return findSubArrayMinimum(a, 0, arraySize - 1) in findSubArray.
If you would implement the tests with arrays of 0, 1, many elements, with the left, right, middle subarrays, you would discover all bugs in your code.
C++ is all about not re-inventing wheels.
#include <algorithm>
size_t findArrayMinimum(int a[], size_t arraySize) {
// Returns index of minimum element
return std::min_element(a, a + arraySize) - a;
}
In your findSubArrayMinumum you need min = a[i]; and not min = i; i is a index and a[i] is value.
I suggested you:
int findSubArrayMinimum(int a[], int arraySize, int left, int right) {
int index = left;
int min = a[left];
for(int i=left;i<right+1;i++){
if(a[i] < min){
min = a[min];
index = i;
}
}
return index;
}
int index = min.findSubArrayMinimum(A,5,1,3);
cout << "Minimum value between [1,2] is at position " << index <<
". and value is: " << A[index] << endl;
int findSubArrayMinimum(int a[], int arraySize, int left, int right) {
//The min is the index of minimum value since you are returning the index only
int min = left;
for(int i=left;i<=right;i++){
//since we have min = indexOfMin, then we need to compare the values
if(a[i] <= a[min]){
min = i;
}
}
//remember! You are returning the index of the minmum value!
return min;
}

Array element number

I need some help with a simple program. And no - its not my homework (I am learning Cpp for myself and maybe use it in future)
So yeah. I have a program, that reads arrays size 10, and then put numbers in it {2.56, 1.598, 0, 5.15, 0, 3.012, 10, 4.789, 2.569, 0}
The program should ignore the 0, and it does, but the problem is.. I need to get the number of the where the number is placed in array
(Smallest number is 1.598 and its 2 in the array)
Meanwhile I get number 8 on the biggest (should be 5 if zeros would be ignored)
and 1 on the smallest. How can I fix that ?
Heres the void of the biggest number :
void Biggest(float array[], int n, float &max, int &maxNr)
{
max = array[0]
for (int i = 1; i < n; i++){
if (array[i] == 0)
continue;
if (array[i] > max){
max = array[i];
maxNr = i;
}
}
}
Printing void :
void Print(float min, float max, double avg, int maxNr, int minNr)
{
ofstream info;
info.open("result1.txt");
info << "Biggest: " << max << " Number : " << maxNr << endl;
info << "Smallest: " << min << " Number : " << minNr << endl;
info << "Average: " << avg << endl;
info.close();
}
And all main.
int main(){
float array[100];
int n;
float max;
float min;
double avg;
int maxNr, minNr;
Reading(array, n);
Biggest(array, n, max, maxNr);
Smallest(array, n, min, minNr);
Average(array, n, avg);
Printing(min, max, avg, maxNr, minNr);
return 0;
}
First of all, array indexes start at 0, not 1.
If you want to get the position ignoreing zeros, you need to use a separate counter variable from the one used to index the array, so that you don't increment it when you skip over 0.
void Biggest(float array[], int n, float &max, int &maxNr)
{
max = array[0];
int position = 0;
for (int i = 0; i < n; i++){
if (array[i] == 0) {
continue;
}
if (array[i] > max){
max = array[i];
}
position++;
}
maxNr = position;
}
Arrays in most (all that I can think of) programming languages start at index zero. So simply change your for loop condition to be:
for (int i = 0; i < n; i++)
Because you want the loop to start at the first element in the array, i must be initialized to 0. That should fix the problem you are having with the array.