#include <iostream>
using namespace std;
int main(){
int a[6] = {5, 2, 4, 6, 1, 3}; // create an array of size 6
int j, key = 0;
for (int i = 1; i < 6; i++) {
key = a[i];
j = i - 1;
while ((j >= 0) && (a[j] > key)) {
a[j + 1] = a[j];
j -= 1;
}
a[j + 1] = key;
}
for (int l = 0; l < 6; l++) {
cout << a[l];
}
return 0;
}
I'm trying to test my insertion sort code using an array
the code complies but when I try to execute the a.out file,
it gives me "Segmentation Fault",
I look up what segmentation fault is, it's basically an error that we are trying to access the forbidden memory location, however, I'm wondering where exactly is the error in my code. Also, if i get rid of the
for (int l = 0; l < 6; l++) {
cout << a[l];
}
no error is found.
Your variable j is not initialized and so may be anything when you first access a[j]. That causes the segmentation fault. (int j,key =0; only sets key to 0 but not j.)
Always compile your code with -Wall, this would have told you about the use of the uninitialized variable. (Correction: My gcc 4.7 doesn't catch it. How lame.)
(The reason why the error goes away when you remove the printing is that you have compiler optimizations turned on: The compiler then notices that you never do anything practical with the computed values and arrays and just throws everything into the bin and gives you an empty program.)
sorting is one of the algorithms in the stl. you should really be using std::sort like
std::sort( a, a+6 );
PS: j is initialized before use in the line
j = i - 1;
so that is not the cause of the crash.
Related
I have following C++ code for bubble sort.
This code compiles without any error, but when I re compile and run, I get
*** stack smashing detected ***: terminated
As a C++ newby I want to know ,why do I get these occasional errors when it runs?
void bubbleSort(int eatenPanCakes[10],int arrSize){
int temp=0;
for(int i=0;i<arrSize-1;i++){
for (int j = 0; j < arrSize-i; j++)
{
if (eatenPanCakes[j] > eatenPanCakes[j+1])
{
temp = eatenPanCakes[j+1];
eatenPanCakes[j+1] = eatenPanCakes[j];
eatenPanCakes[j] = temp;
}
}
}
}
Environment : g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
There is a bug in my code : for (int j = 0; j+1 < arrSize-i; j++) would be the right algorithm and that works without error.
Ref-1,Ref-2
You program is accessing array beyond its size which is an undefined behavior. Check this for loop condition:
for (int j = 0; j < arrSize-i; j++)
[I believe, arrSize value is 10 as the type of eatenPanCakes array is int [10]].
when i is 0, arrSize-i value is 10 and in last iteration when j value is 9, this statement
if (eatenPanCakes[j] > eatenPanCakes[j+1])
access j+1th element of eatenPanCakes array which is element at index 10. Note that an array of size 10 will have valid index from 0 to 9.
Instead, the condition in for loop should be
for (int j = 0; j < arrSize - i - 1; j++)
^^^
because the jth element is compared with element ahead of it in the array.
I wrote this knapsack problem solution in c++ however when I run it, it gives me segmentation fault
I have tried everything and my compiler will always give me the segmentation fault error.
#include<iostream>
#include<algorithm>
int knapsack(int v[],int w[],int n,int W)
{
int V[n][W];
for(int i = 0; i<=W;i++)
{
V[0][i] = 0;
}
for(int i = 0; i <= n; i++){
for(int j = 1; j<=W; j++)
{
if(w[i]<=W)
{
V[i][j] = std::max(V[i-1][j], v[i]+V[i-1][j-w[i]]);
}
else
{
V[i][j] = V[i-1][j];
}
}
}
return V[n][W];
}
int main()
{
int v[4] = {10,40,30,50};
int w[4] = {5,4,6,3};
int n = 3;
int W = 10;
std::cout<<"item value:"<<knapsack(v,w,n,W);
}
Don't use VLAs. The size of an array must be known at compile time, else it's not standard C++. Those are compiler extensions that are not portable and introduce some hidden costs.
Array indices go from 0 to length-1. in you loop
for(int i = 0; i<=W;i++)
i can reach W, then V[0][W] is out of bounds which causes the seg fault. You have to use < instead of <=:
for(int i = 0; i < W; i++)
n should probably be 4, if it's meant to represent the size of the array, a std::vector would make your life easier here, because a vector knows it's size
In general don't use C-style arrays or raw pointers at all in this day and age, use std::vector instead.
int V[n][W];
for(int i = 0; i<=W;i++)
{
V[0][i] = 0;
}
Note that V's indexes go from V[0][0] to V[0][W-1]. Your for loop will try to read V[0][W].
The same error is repeated in other places. Your end condition in your for loops should be < (strictly less) instead of <= (less or equal than).
I'm in a linux server and when I try to execute the program it's returning a segmentation fault. when i use gdb to try and find out why, it returns..
Starting program: /home/cups/k
Program received signal SIGSEGV, Segmentation fault.
0x0000000000401128 in search(int) ()
Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.192.el6.x86_64 libgcc-4.4.7-17.el6.x86_64 libstdc++-4.4.7-17.el6.x86_64
I couldn't quite interpret this. In my program i have a function called "search()" but i don't see anything that would cause a seg fault. here's the function def:
int search (int bit_type) { // SEARCH FOR A CONSEC NUMBER (of type BIT_TYPE) TO SEE IF ALREADY ENCOUNTERED
for (int i = 1; i <= MAX[bit_type]; i++) { //GO THRU ALL ENCOUNTERED CONSEC NUMBERS SO FAR (for type BIT_TYPE)
if (consec == r[bit_type][i]) // IF: FOUND
return i; // -----> RETURN INDEX OF RECORDED CONSEC_NUM
}
// IF: NOT FOUND
r[bit_type][++MAX[bit_type]] = consec; // -----> INCREMENT MAX[bit_type] & RECORD NEW CONSEC_NUM -------> ARRAY[MAX]
n[bit_type][MAX[bit_type]] = 1;
return (MAX[bit_prev]); // -----> RETURN THE NEWLY FILLED INDEX
}
global functions:
int MAX[2];
int r[2][200];
int n[2][200];
The comments are pretty useless to you guys since you don't have the rest of the program.. but you can just ignore them.
But do you guys see anything I missed?
From the link to your code here, here is just one error:
int *tmp = new int[MAX[0]];
for (int y = 0; y <= MAX[0]; y++) {
tmp[y] = 1;
}
You are going out-of-bounds on the last iteration. You allocated an array with MAX[0] items, and on the last iteration you're accessing tmp[MAX[0]].
That loop should be:
int *tmp = new int[MAX[0]];
for (int y = 0; y < MAX[0]; y++) {
tmp[y] = 1;
}
or better yet:
#include <algorithm>
//...
std::fill(tmp, tmp + MAX[0], 1); // no loop needed
or skip the dynamic allocation using new[] and use std::vector:
#include <vector>
//...
std::vector<int> tmp(MAX[0], 1);
In general, you have multiple loops that do this:
for (int i = 1; i <= number_of_items_in_array; ++i )
and then you access your arrays with array[i]. It is the <= in that for loop condition that is suspicious since it will try to access the array with an out-of-bounds index on the last iteration.
Another example is this:
long sum(int arr_r[], int arr_n[], int limit)
{
long tot = 0;
for (int i = 1; i <= limit; i++)
{
tot += (arr_r[i])*(arr_n[i]);
}
return tot;
}
Here, limit is the number of elements in the array, and you access arr_r[i] on the last iteration, causing undefined behavior.
Arrays are indexed starting from 0 and up to n - 1, where n is the total number of elements. Trying to fake 1-based arrays as you're attempting to do almost always results in these types of errors somewhere inside of the code base.
I am having trouble with the _mm_store_ps command. I am getting a segmentation fault when I use it (and I know that is the problem because when I comment out that line the segmentation fault goes away). It is strange though because I am using a static array which I manually ask the compiler to align, and using _mm_storeu_ps does not make the problem go away. Here is the relevant section of code:
//Directly access array instead of using Boost interface
boost::numeric::ublas::matrix<float>::iterator2 it = result.begin2();
float temp[4] __attribute__((aligned__(16))), temp2 = 0;
//Use SSE
__m128 m1, sse_right1, sse_left1, store_sse __attribute__((aligned (16))) = _mm_set_ps1(0);
unsigned k = 0;
//Iterate over the dimensions of the matrices
for (unsigned i = 0; i < ls1; i++)
{
for (unsigned j = 0; j < rs2; j++)
{
while (k + 3 < ls2)
{
sse_right1 = _mm_load_ps(arr + k + j * rs1);
sse_left1 = _mm_load_ps(left_arr + k + i * ls2);
m1 = _mm_mul_ps(sse_right1, sse_left1);
store_sse = _mm_add_ps(store_sse,m1);
k += 4;
}
//If ls2 isn't divisible by 4
while (k < ls2)
{
temp2 += left_arr[i * ls2 + k] * arr[k + j * rs1];
k++;
}
if (ls2 >= 4)
{
_mm_store_ps(temp, store_sse);
for (unsigned l = 0; l < 4; l++)
{
temp2 += temp[l];
}
}
*it = temp2;
store_sse = _mm_set_ps1(0);
temp2 = 0;
k = 0;
it++;
}
The segmentation fault isn't a problem with the array bounds because the execution makes it down to the _mm_store_ps line. Any help would be appreciated, thanks!
Edit: The problem is with _mm_load_ps, when I use _mm_loadu_ps it runs fine. I am using static arrays as the arguments to _mm_load_ps, so I don't know why I am having problems.
SSE requires its memory access to be with 16-byte aligned addresses. If you're not reading from outside of the array, this is likely your problem.
Try using _mm_storeu_ps and _mm_loadu_ps, which are unaligned versions. They will run a little slower, but they will work. After you've verified that's the problem, try aligning the memory in the first place for maximum performance.
I seem to be having some trouble getting this mergesort to run. When I try to run it with g++ the terminal says "Segmentation fault (core dumped)," and I don't know what is causing this to happen (you might be able to tell that I'm still a beginner). Could anybody help out?
#include <iostream>
using namespace std;
void merge (int*, int, int, int);
void mergesort (int* A, int p, int r){
if (p < r){
int q = (p+r)/2;
mergesort (A, p, q);
mergesort (A, q+1, r);
merge ( A, p , q, r);
}
}
void merge (int* A, int p, int q, int r){
int n = q-p+1;
int m = r-q ;
int L [n+1];
int R [m+1];
for (int i=1;i <n+1;i++)
L[i] = A[p+i-1];
for (int j=1; j< m+1; j++)
R[j] = A[q+j];
L[n+1];
R[m+1];
int i= 1;
int j=1;
for (int k = p; k= r + 1; k++){
if (L[i] <= R[j]){
A[k] = L[i];
i+=1;
}
else{
j += 1;
}
}
}
int main() {
int A [15] = {1, 5, 6, 7,3, 4,8,2,3,6};
mergesort (A, 0, 9);
for (int i=0; i <9; i++){
cout << A[i] << endl;
}
return 0;
}
Thanks a lot!
There are three things in your implementation that either don't make sense or are outright wrong:
First these:
L[n+1];
R[m+1];
Neither of these statement have any effect at all, and I've no idea what you're trying to do.
Next, a significant bug:
for (int k = p; k= r + 1; k++){
The conditional clause of this for-loop is the assignment k = r + 1. Since r does not change anywhere within your loop, the only way that expression is false is if r == -1, which it never is. You've just created an infinite-loop on a counter k that will run forever up into the stratosphere, and in the process index, and write, to memory no longer valid in your process. This, as a result, is undefined behavior. I'm fairly sure you wanted this:
for (int k = p; k< (r + 1); k++){
though I can't comment on whether that is a valid limit since I've not dissected your algorithm further. I've not take the time to debug this any further. that I leave to you.
Edit. in your main mergsesort, this is not "wrong" but very susceptible to overflow
int q = (p+r)/2;
Consider this instead:
int q = p + (r-p)/2;
And not least this:
int L [n+1];
int R [m+1];
Uses a variable-length array extension not supported by the standard for C++. You may want to use std::vector<int> L(n+1) etc.. instead.
In your case the segmentation fault is likely being caused when you are trying to read memory in that does not exist for a variable, for example say you have an array called foo of size 10 (so foo[10]) and you this statement foo[11] would cause a segmentation fault.
What you need to do is use debug statements to print out your index variables (i, j, n, m, p and q) and see if any of these are larger than your array sizes
EDIT: Another unrelated issue is that you should not use using namespace std, this line of code can cause scoping issues if you are not careful, just something to keep in mind :)