Getting segmentation fault (or bad access) for some inputs and the program halts - vector

#include <iostream>
#include <vector>
#include <string>
using namespace std;
void step_selection_sort(vector <int> &a, int size, int idx){
int i,j,min,temp;
i = idx;
min = i;
for (j=i+1;j<size;j++)
{
if (a[min]>a[j])
min=j;
}
if (min!=i)
{
temp = a[i];
a[i] = a[min];
a[min] = temp;
}
idx++;
}
void selection_sort(vector <int> &a, int size, int idx){
int i;
for(i=0;i<size;i++)
{
step_selection_sort(a,size,idx);
}
}
void step_desc_sort(vector <int>& a, int size, int idx){
int i,j,max,temp;
i = idx;
max = i;
for (j=i+1;j<size;j++)
{
if (a[max]<a[j])
max=j;
}
if (max!=i)
{
temp = a[i];
a[i] = a[max];
a[max] = temp;
}
idx++;
}
void desc_sort(vector <int>& a, int size, int idx){
int i;
for(i=0;i<size;i++)
{
step_desc_sort(a,size,idx);
}
}
void swap (int & a, int & b)
{
int t = a;
a = b;
b = t;
}
int findCeil (vector <int>& nums, int first, int begin, int end)
{
int ceilIndex = begin;
for (int i = begin+1; i <= end; i++)
if (nums[i] > first && nums[i] < nums[ceilIndex])
ceilIndex = i;
return ceilIndex;
}
int findBottom(vector <int>& nums,int first,int begin,int end)
{
int bottomIndex = begin;
for (int i = begin+1; i <= end; i++)
if (nums[i] < first && nums[i] > nums[bottomIndex])
bottomIndex = i;
return bottomIndex;
}
void sortedPermutations_ASC (vector <int> nums,int num)
{
bool isfinished=false;
if(isfinished==false)
for(int i=0;i<num;i++)
cout << nums[i]; //bad access when giving inputs bigger than 8
cout << endl;
int k;
for ( k = num - 2; k >= 0; --k )
if (nums[k] < nums[k+1])
break;
if ( k == -1 )
isfinished=true;
else
{
int ceilIndex = findCeil( nums, nums[k], k + 1, num - 1 );
swap( nums[k], nums[ceilIndex] );
selection_sort(nums,num,k+1);
sortedPermutations_ASC(nums,num);
}
}
void sortedPermutations_DESC (vector <int> nums,int num)
{
int i;
bool isfinished=false;
if(isfinished==false)
for(i=0;i<num;i++)
cout << nums[i];
cout << endl;
int k;
for ( k = num - 2; k >= 0; --k )
if (nums[k] > nums[k+1])
break;
if ( k == -1 )
isfinished=true;
else
{
int bottomIndex = findBottom( nums, nums[k], k + 1, num - 1 );
swap( nums[k], nums[bottomIndex] );
desc_sort(nums,num,k+1);
sortedPermutations_DESC(nums,num);
}
return;
}
int main(){
vector <int> nums;
string line,temp;
int num,j,k;
getline(cin,line);
while(j<line.size() && line[j]!=' ')
j++;
num=stoi(line.substr(0,j));
string kind;
j++;
kind=line.substr(j);
if(kind=="ASC"){
for(k=0;k<num;k++)
nums.push_back(k+1);
sortedPermutations_ASC(nums,num);
}
if(kind=="DESC"){
for(k=0;k<num;k++)
nums.push_back(num-k);
sortedPermutations_DESC(nums,num);
}
return 0;
}
here's is my code. it gives the permutations of a number.It works properly when inputs are between 1 and 8 .But it doesn't work with numbers bigger than 8 .
for example if I give
9 ASC (it means in Ascending order)
to the program , I get "Segmentation Fault:11" in terminal (mac) after printing some of the permutations .
I tried running it in Xcode . with the same input it says :
Thread 1:EXC_BAD_ACCESS(code=2,address=0x7ffff5f3fffc8)
for the line that I put comment in front of it .
I don't know what to do anymore ...
Any help would be appreciated - thanks in advance

Related

Stuck at solving leetcode Q5 using C [=34==ERROR: AddressSanitizer]

Please excuse for my massy code. This was best I could do.
I have been solving leetcode Q5 for a while; however, I couldn't solve it. This is the closest answer I have got.
I think it's acting correctly in terms of showing outputs. But has a runtime error when
let s = "tscvrnsnnwjzkynzxwcltutcvvhdivtmcvwdiwnbmdyfdvdiseyxyiiurpnhuuufarbwalzysetxbaziuuywugfzzmhoessycogxgujmgvnncwacziyybryxjagesgcmqdryfbofwxhikuauulaqyiztkpgmelnoudvlobdsgharsdkzzuxouezcycsafvpmrzanrixubvojyeuhbcpkuuhkxdvldhdtpkdhpiejshrqpgsoslbkfyraqbmrwiykggdlkgvbvrficmiignctsxeqslhzonlfekxexpvnblrfatvetwasewpglimeqemdgdgmemvdsrzpgacpnrbmomngjpiklqgbbalzxiikacwwzbzapqmatqmexxqhssggsyzpnvvpmzngtljlrhrjbnxgpcjuokgxcbzxqhmitcxlzfehwfiwcmwfliedljghrvrahlcoiescsbupitckjfkrfhhfvdlweeeverrwfkujjdwtcwbbbbwctwdjjukfwrreveeewldvfhhfrkfjkctipubscseioclharvrhgjldeilfwmcwifwhefzlxctimhqxzbcxgkoujcpgxnbjrhrljltgnzmpvvnpzysggsshqxxemqtamqpazbzwwcakiixzlabbgqlkipjgnmombrnpcagpzrsdvmemgdgdmeqemilgpwesawtevtafrlbnvpxexkeflnozhlsqexstcngiimcifrvbvgkldggkyiwrmbqaryfkblsosgpqrhsjeiphdkptdhdlvdxkhuukpcbhueyjovbuxirnazrmpvfascyczeuoxuzzkdsrahgsdbolvduonlemgpktziyqaluuaukihxwfobfyrdqmcgsegajxyrbyyizcawcnnvgmjugxgocysseohmzzfguwyuuizabxtesyzlawbrafuuuhnpruiiyxyesidvdfydmbnwidwvcmtvidhvvctutlcwxznykzjwnnsnrvcst"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int is_palindrome(char * s);
void get_substring(const char *str, char *substr, int start, int end);
char * longestPalindrome(char * s){
int strlength = strlen(s);
int end = strlength - 1;
int start = 0;
char substr[1000];
char *longstr = (char *)malloc(1000 * sizeof(char));
strcpy(longstr, "");
while (start <= end)
{
get_substring(s, substr, start, end);
// printf("%s\n", substr);
if (is_palindrome(substr) > strlen(longstr))
{
// printf("UPDATE : %s\n", substr);
strcpy(longstr, substr);
}
if (end == start)
{
start++;
end = strlength - 1;
}
else
{
end--;
}
}
// printf("LONG : %s", longstr);
return longstr;
}
void get_substring(const char *str, char *substr, int start, int end) {
int length = end - start + 1;
strncpy(substr, str + start, length);
substr[length] = '\0';
}
int is_palindrome(char * s){
int length = strlen(s);
int mid = length/2;
if (length % 2 == 0)
{
// printf("EVEN : %d\n", mid);
mid--;
int upperptr = mid+1;
int i = 0;
if (s[mid] != s[upperptr])
{
// printf("Returning FALSE [0]\n");
return 0;
}
while (mid-i >= 0 && upperptr+i <= length)
{
// printf("%c and %c and mid is %c\n", s[mid-i], s[upperptr+i], s[mid]);
if (s[mid-i] != s[upperptr+i])
{
// printf("Returning FALSE [1]\n");
return 0;
}
i++;
}
}
else
{
// printf("ODD: %d\n", mid+1);
int i = 0;
while (mid-i >= 0 && mid+i <= length)
{
// printf("%c and %c and mid is %c\n", s[mid-i], s[mid+i], s[mid]);
if (s[mid-i] != s[mid+i])
{
// printf("Returning FALSE [2]\n");
return 0;
}
i++;
}
}
// printf("Returning TRUE\n");
return length;
}
I had difficulties returning a local string. then found out that local string value can't be returned and has to be dynamically malloced and the pointer has to be returned.
So I fixed it (somehow, if it is right). But I reckon this is causing different - even harder - problems that I can't manage.

Next greater element using recursion

I have seen the problem of finding the next greater element for each element in an array and it can be easily solved using monotonic stack. But can it be solved using recursion?
For the input array [4, 5, 2, 25], the next greater elements for each element are as follows.
4 --> 5
5 --> 25
2 --> 25
25 --> -1
Using stack
#include <bits/stdc++.h>
using namespace std;
void printNGE(int arr[], int n)
{
stack<int> s;
int res[n];
for (int i = n - 1; i >= 0; i--) {
if (!s.empty()) {
while (!s.empty() && s.top() <= arr[i]) {
s.pop();
}
}
res[i] = s.empty() ? -1 : s.top();
s.push(arr[i]);
}
for (int i = 0; i < n; i++)
cout << arr[i] << " --> " << res[i] << endl;
}
int main()
{
int arr[] = { 11, 13, 21, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
printNGE(arr, n);
return 0;
}
long long fun(long long i,vector<long long>&v,long long par)
{
if(i==v.size())
return -1;
if(v[i]>v[par])
{
return v[i];
}
return fun(i+1,v,par);
}
void solve(long long i,vector<long long>&v,vector<long long>&ans)
{
if(i==v.size())return ;
solve(i+1,v,ans);
long long temp=fun(i+1,v,i);
ans[i]=temp;
}
vector<long long> nextLargerElement(vector<long long> v, int n)
{
vector<long long>ans(n,-1);
solve(0,v,ans);
return ans;
}

What is the most optimised way to print the path from root to every leaf of a tree?

Input
T- test cases
N-no of nodes
N-1 lines follow
x y - there is an edge between x and y
1
5
1 2
2 5
1 3
3 4
Output
Path 1 3 4
Path 1 2 5
Approach
First I do a BFS on the tree and store all the parent values for every
node.Then, for every leaf node, I backtrack to the root using the
parent values.I push them to a path vector and print the path vector.
However, I think the solution is very time inefficient. Can you
suggest a better way?
My code- it is getting TLE
void bfs(vector<int> adj[], int start, int n, int val[], int mod[]) {
int parent[n + 1];
bool visited[n + 1];
memset(visited, false, sizeof(visited));
for (int i = 1; i <= n; ++i)
{
/* code */
parent[i] = -1;
}
queue<int> q;
q.push(start);
parent[start] = -1;
visited[start] = true;
while (!q.empty()) {
int x;
x = q.front();
q.pop();
for (auto u : adj[x]) {
if (!visited[u]) {
q.push(u);
parent[u] = x;
visited[u] = true;
}
}
}
vector<int> leaf;
//check if a leaf node
for (int i = 1; i <= n; i++) {
if (adj[i].size() == 1)
leaf.pb(i);
}
for (auto x : leaf) {
vector<int> path;
for (int v = x; v != -1; v = parent[v])
path.push_back(val[v]);
cout<<"Path"<<" ";
for(auto x:path)
cout<<x<<" ";
cout<<endl;
}
}
int main(){
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
std::vector<int> adj[n + 1];
int edges = n - 1;
while (edges--) {
int x, y;
cin >> x >> y;
adj[x].pb(y);
adj[y].pb(x);
}
int val[n + 1];
int mod[n + 1];
for (int i = 1; i <= n; i++) {
/* code */
cin >> val[i];
}
for (int i = 1; i <= n; i++) {
/* code */
cin >> mod[i];
}
bfs(adj, 1, n, val, mod);
cout<<endl;
return 0;
}

Unhandled exception error with two dimensional array

This dynamic programming algorithm is returning unhandled exception error probably due to the two dimensional arrays that I am using for various (and very large) number of inputs. I can't seem to figure out the issue here. The complete program as follows:
// A Dynamic Programming based solution for 0-1 Knapsack problem
#include<stdio.h>
#include<stdlib.h>
#define MAX 10000
int size;
int Weight;
int p[MAX];
int w[MAX];
// A utility function that returns maximum of two integers
int maximum(int a, int b) { return (a > b) ? a : b; }
// Returns the maximum value that can be put in a knapsack of capacity W
int knapSack(int W, int wt[], int val[], int n)
{
int i, w;
int retVal;
int **K;
K = (int**)calloc(n+1, sizeof(int*));
for (i = 0; i < n + 1; ++i)
{
K[i] = (int*)calloc(W + 1, sizeof(int));
}
// Build table K[][] in bottom up manner
for (i = 0; i <= n; i++)
{
for (w = 0; w <= W; w++)
{
if (i == 0 || w == 0)
K[i][w] = 0;
else if (wt[i - 1] <= w)
K[i][w] = maximum(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]);
else
K[i][w] = K[i - 1][w];
}
}
retVal = K[n][W];
for (i = 0; i < size + 1; i++)
free(K[i]);
free(K);
return retVal;
}
int random_in_range(unsigned int min, unsigned int max)
{
int base_random = rand();
if (RAND_MAX == base_random) return random_in_range(min, max);
int range = max - min,
remainder = RAND_MAX % range,
bucket = RAND_MAX / range;
if (base_random < RAND_MAX - remainder) {
return min + base_random / bucket;
}
else {
return random_in_range(min, max);
}
}
int main()
{
srand(time(NULL));
int val = 0;
int i, j;
//each input set is contained in an array
int batch[] = { 10, 20, 30, 40, 50, 5000, 10000 };
int sizeOfBatch = sizeof(batch) / sizeof(batch[0]);
//algorithms are called per size of the input array
for (i = 0; i < sizeOfBatch; i++){
printf("\n");
//dynamic array allocation (variable length to avoid stack overflow
//calloc is used to avoid garbage values
int *p = (int*)calloc(batch[i], sizeof(int));
int *w = (int*)calloc(batch[i], sizeof(int));
for (j = 0; j < batch[i]; j++){
p[j] = random_in_range(1, 500);
w[j] = random_in_range(1, 100);
}
size = batch[i];
Weight = batch[i] * 25;
printf("| %d ", batch[i]);
printf(" %d", knapSack(Weight, w, p, size));
free(p);
free(w);
}
_getch();
return 0;
}
Change this:
for (i = 0; i < size + 1; i++)
free(K[i]);
free(K);
return K[size][Weight];
To this:
int retVal;
...
retVal = K[size][Weight];
for (i = 0; i < size + 1; i++)
free(K[i]);
free(K);
return retVal;

OpenCL : UNREACHABLE executed

I have the generic kernel that calculates part sums of array elements in temporary buffer.
#if FUNC_SUM
#define FUNC(a, b) b += a;
#elif FUNC_ABS_SUM
#define FUNC(a, b) b += a >= (dstT)(0) ? a : -a;
#elif FUNC_SQR_SUM
#define FUNC(a, b) b += a * a;
#else
#error No sum function
#endif
__kernel void sum(int cols,int invalid_cols,int offset,int elemnum,int groupnum,
__global srcT *src, __global dstT *dst)
{
int lid = get_local_id(0);
int gid = get_group_id(0);
int id = get_global_id(0);
int idx = offset + id + (id / cols) * invalid_cols;
__local dstT localmem_sum[128];
dstT sum = (dstT)(0), temp;
for (int grainSize = groupnum << 8; id < elemnum; id += grainSize)
{
idx = offset + id + (id / cols) * invalid_cols;
temp = convertToDstT(src[idx]);
FUNC(temp, sum);
}
if (lid > 127)
localmem_sum[lid - 128] = sum; // ??
barrier(CLK_LOCAL_MEM_FENCE);
if (lid < 128)
localmem_sum[lid] = sum + localmem_sum[lid];
barrier(CLK_LOCAL_MEM_FENCE);
for (int lsize = 64; lsize > 0; lsize >>= 1)
{
if (lid < lsize)
{
int lid2 = lsize + lid;
localmem_sum[lid] = localmem_sum[lid] + localmem_sum[lid2];
}
barrier(CLK_LOCAL_MEM_FENCE);
}
if (lid == 0)
dst[gid] = localmem_sum[0];
}
And this code fails with the message "UNREACHABLE executed!" on the line marked as // ??
Any wrong in this code? does some workaround exist to avoid this error?
Target platform: AMD GPU

Resources