Why does this doesnt work for transposing a matrix - pointers

For some reason the element b[m][n] is a random number instead of being 1. The same thing happens if I try to printf a[n][m]. Please I need some help on this!
#include <stdio.h>
#include <stdlib.h>
void **alloc(int n,int m)
{
int **x=(int**)malloc(n*sizeof(int*));
for(int i=1; i<=n; i++)
x[i] =(int*)malloc(m*sizeof(int*));
return x ;
}
void read(int **a,int n,int m,FILE *f)
{
for(int i=1; i<=n; i++)
for(int j=1; j<=m; j++)
fscanf(f,"%d",&a[i][j]);
}
void print(int **a,int n,int m)
{
for(int i=1; i<=n; i++)
{
for(int j=1; j<=m; j++)
printf("%d ",a[i][j]);
printf("\n");
}
}
void transpose(int **a,int n,int m,int ***b)
{
for(int i=1; i<=n; i++)
for(int j=1; j<=m; j++)
b[j][i]=a[i][j];
}
int main()
{
int n,m;
FILE *f;
f=fopen("in.txt","r");
if(f==NULL)
printf("Error");
fscanf(f,"%d %d",&n,&m);
int **a=alloc(n,m);
read(a,n,m,f);
int **b=alloc(m,n);
transpose(a,n,m,b);
print(b,m,n);
return 0;
}
This is the input and output, everything works except the b[m][n] element

There are several issues:
If this is C code, casting the result of malloc is at best pointless and at worst dangerous, as it might hide bugs. (This does not apply for C++ code.)
Your "inner" malloc uses sizeof(int*), when it should be using sizeof(int).
Your alloc function returns void**, which is not wrong as such, but why not let it return int** instead?
This is the most important one: C array indexing starts at zero, so if you have an array of N elements, they are numbered 0 though N-1.

Related

How to solve this ==31==error Address sanitizer heap buffer overflow error?

/**
* Note: The returned array must be malloced, assume caller calls free().
*/
char memo[10];
int count[500]={0,};
typedef struct Trie{
int count;
struct Trie * next[26];
}Trie;
void Initnode(struct Trie *node){
node->count=0;
for(int i=0;i<26;i++){
node->next[i]=NULL;
}
}
void fixtrie(struct Trie *root, char *wordsitem){
int pw=0;
struct Trie* cur=root;
while(wordsitem[pw]!='\0'){
if(cur->next[wordsitem[pw]-'a']==NULL){
cur->next[wordsitem[pw]-'a']=malloc(sizeof(struct Trie));
Initnode(cur->next[wordsitem[pw]-'a']);
cur=cur->next[wordsitem[pw]-'a'];
pw++;
}
else{
cur=cur->next[wordsitem[pw]-'a'];
pw++;
}
}
(cur->count)++;
}
void dfs(struct Trie *root, char**result, int k,int pm){
if(root->count>0){
for(int i=0;i<k;i++){
if(root->count >count[i]){
for(int j=k-1;j>i;j--){
for(int c=0;c<10;c++) result[j][c]=result[j-1][c];
count[j]=count[j-1];
}
count[i]=root->count;
for(int j=0;j<10;j++) result[i][j]=0;
for(int j=0;j<pm;j++){
result[i][j]=memo[j];
}
printf("// %s //",result[i]);
break;
}
}
}
printf(" %d ",pm);
for(int i=0;i<26;i++){
if(root->next[i]!=NULL){
printf(" %d ",pm);
memo[pm]= i+'a';
printf("%s",memo);
dfs(root->next[i],result,k,pm+1);
}
}
return;
}
char ** topKFrequent(char ** words, int wordsSize, int k, int* returnSize){
for(int j=0;j<500;j++){
count[j]=0;
}
for(int j=0;j<10;j++){
memo[j]=0;
}
*returnSize=k;
struct Trie* root=malloc(sizeof(struct Trie)*1);
Initnode(root);
for(int i=0;i<wordsSize;i++){
fixtrie(root,words[i]);
}
for(int i=0;i<26;i++){
if(root->next[i]!=NULL){
}
}
char**result=(char**) malloc (sizeof(char*)*k);
for(int i=0;i<k;i++){
result[i]=malloc(sizeof(char)*10);
}
dfs(root,result,k,0);
printf("happy");
for(int i=0;i<k;i++){
printf("\n %s",result[i]);
}
printf("\n");
return result;
}
This problem is 692.problem of Leetcode.
I detect when words[I].length equals to 10, error occurs. but I don't know how to fix this code.
Input which occurs error is that ["glarko","zlfiwwb","nsfspyox","pwqvwmlgri","qggx","qrkgmliewc","zskaqzwo","zskaqzwo","ijy","htpvnmozay","jqrlad","ccjel","qrkgmliewc","qkjzgws","fqizrrnmif","jqrlad","nbuorw","qrkgmliewc","htpvnmozay","nftk","glarko","hdemkfr","axyak","hdemkfr","nsfspyox","nsfspyox","qrkgmliewc","nftk","nftk","ccjel","qrkgmliewc","ocgjsu","ijy","glarko","nbuorw","nsfspyox","qkjzgws","qkjzgws","fqizrrnmif","pwqvwmlgri","nftk","qrkgmliewc","jqrlad","nftk","zskaqzwo","glarko","nsfspyox","zlfiwwb","hwlvqgkdbo","htpvnmozay","nsfspyox","zskaqzwo","htpvnmozay","zskaqzwo","nbuorw","qkjzgws","zlfiwwb","pwqvwmlgri","zskaqzwo","qengse","glarko","qkjzgws","pwqvwmlgri","fqizrrnmif","nbuorw","nftk","ijy","hdemkfr","nftk","qkjzgws","jqrlad","nftk","ccjel","qggx","ijy","qengse","nftk","htpvnmozay","qengse","eonrg","qengse","fqizrrnmif","hwlvqgkdbo","qengse","qengse","qggx","qkjzgws","qggx","pwqvwmlgri","htpvnmozay","qrkgmliewc","qengse","fqizrrnmif","qkjzgws","qengse","nftk","htpvnmozay","qggx","zlfiwwb","bwp","ocgjsu","qrkgmliewc","ccjel","hdemkfr","nsfspyox","hdemkfr","qggx","zlfiwwb","nsfspyox","ijy","qkjzgws","fqizrrnmif","qkjzgws","qrkgmliewc","glarko","hdemkfr","pwqvwmlgri"]
14
I expect well answer.
But it occurs
enter image description here
How to fix my code?

the count of subsequence of aray where arr[i]-arr[i-1] is constant for the array

we are given an array and its size and a interger k we need to find all/count of all subsequence that has constant arr[i]-arr[i-1] diff for all element and it size should be k
i have tryed my approach and it is clear to understand also but it just printing count i.e cnt as 0 why any one
#include<bits/stdc++.h>
#include
using namespace std;
void subseq(vector<int>&arr,int idx,int n,int k,int& cnt,vector<int>&nums){
if(idx==n-1){
if(nums.size()==k){
bool flag=1;
int dist=nums[1]-nums[0];
for(int i=2;i<n;i++){
if(nums[i]-nums[i-1]==dist){
continue;
}else{
flag=0;
}
}
if(flag)
cnt+=1;
}
return;
}
nums.push_back(arr[idx]);
subseq(arr,idx+1,n,k,cnt,nums);
nums.pop_back();
subseq(arr,idx+1,n,k,cnt,nums);
}
int main(){
int t;
cin>>t;
while(t--){
int n,m;
cin>>n>>m;
vector<int>v(n);
// cout<<1<<endl;
for(int i=0;i<n;i++)
cin>>v[i];
vector<int>x;
int cnt=0;
// cout<<1<<endl;
subseq(v,0,n,m,cnt,x);
cout<<cnt<<endl;
}
return 0;
}

Segmentation fault inside range

#include <iostream>
#include <vector>
#include <algorithm>
#include <queue> // std::priority_queue
using std::vector;
using std::cin;
using std::cout;
struct fj{
int indexI=0;
int freeT=0;
};
struct DereferenceCompareNode : public std::binary_function<fj, fj, bool>
{
bool operator()(const fj lhs, const fj rhs) const
{
return lhs.freeT > rhs.freeT;
}
};
class JobQueue {
private:
int num_workers_;
vector<int> jobs_;
vector<int> assigned_workers_;
vector<long long> start_times_;
void WriteResponse() const {
for (int i = 0; i < jobs_.size(); ++i) {
cout << assigned_workers_[i] << " " << start_times_[i] << "\n";
}
}
void ReadData() {
int m;
cin >> num_workers_ >> m;
jobs_.resize(m);
std::cout<<"Read fault"<<"\n";
for(int i = 0; i < m; i++)
cin >> jobs_[i];
std::cout<<"Read fault ends"<<"\n";
}
void AssignJobs() {
// TODO: replace this code with a faster algorithm.
std::cout<<"Fault point 1"<<"\n";
assigned_workers_.resize(jobs_.size());
start_times_.resize(jobs_.size());
vector<long long> next_free_time(num_workers_, 0);
std::priority_queue<int, vector<int>, std::greater<int> > thread;
std::priority_queue<fj, vector<fj>, DereferenceCompareNode > freeJob;
/*
for (int i = 0; i < jobs_.size(); ++i) {
int duration = jobs_[i];
int next_worker = 0;
for (int j = 0; j < num_workers_; ++j) {
if (next_free_time[j] < next_free_time[next_worker])
next_worker = j;
}
assigned_workers_[i] = next_worker;
start_times_[i] = next_free_time[next_worker];
next_free_time[next_worker] += duration;
}
*/
std::cout<<"dump point 2"<<"\n";
for(int i=0;i<num_workers_;i++){
thread.push(i);
}
std::cout<<"dump point 1"<<"\n";
int counter = 0;
while(jobs_.size()!=0){
std::cout<<"jobs_.size:"<<jobs_.size()<<"\n";
std::cout<<"freeJob.size:"<<freeJob.size()<<"\n";
//check logic
do{
if(freeJob.top().freeT == counter){
std::cout<<"freeJob.top().freeT:"<<freeJob.top().freeT<<"\n";
std::cout<<"counter:"<<counter<<"\n";
thread.push(freeJob.top().indexI);
freeJob.pop();
}else{
break;
}
}
while(freeJob.size()!=0);
std::cout<<"Thread:"<<thread.size()<<"\n";
while(thread.size()!=0){
if(jobs_.size()!=0){
fj currA;
currA.indexI = thread.top();
currA.freeT = jobs_.at(0)+counter;
std::cout<<"currA.indexI:"<<currA.indexI<<"\n";
std::cout<<"currA.freeT:"<<currA.freeT<<"\n";
thread.pop();
jobs_.erase(jobs_.begin());
assigned_workers_.push_back(currA.indexI);
start_times_.push_back(currA.freeT);
}else{
break;
}
}
counter++;
}
}
public:
void Solve() {
ReadData();
AssignJobs();
WriteResponse();
}
};
int main() {
std::ios_base::sync_with_stdio(false);
JobQueue job_queue;
job_queue.Solve();
return 0;
}
I am getting segmentation fault in function ReadData while taking inputs for vector jobs.
I am getting fault even when I am inside bounds of defined size.
Everything was fine when have not written AssignJob function.
Am I doing something wrong with some bounds or taking illegal inputs format or messing with some other stuff?
Am I doing something wrong
Yes, you are: freeJob starts out empty, so this is undefined behavior:
if(freeJob.top().freeT == counter){
In fact, you never push anything into freeJob, you only pop() things from it.

ArrayIndexOutOfBoundsException - why am I still having this problem?

I'm trying to print a chessboard to the console using a 2D array. For testing purposes, I'm trying to simply populate the board as 'x' chars. However, I keep getting an ArrayIndexOutOfBounds exception when I try to populate the array with the following:
public void setupBoard(){
for (int i=0; i < height; i++){
for (int j=0; j < width; j++){
boardArray[i][j] = 'x';
}
}
}
The error apparently occurs at boardArray[i][j] = 'x';
Everything seems to be in order, I dont see why this isnt working.
EDIT: I got the array to populate, but now I cannot format the printing correctly. The contents all print on one line, instead of as an 8x8 square of 'x' chars. Here's what I have now:
public void displayBoard(){
for (int k=0; k < boardArray.length; k++)
for (int l=0; l < boardArray[k].length; l++){
System.out.print(boardArray[k][l]);
}
System.out.println();
}
Well, presumably it's because you haven't created the board properly. Unfortunately you haven't shown us the array creation statement. It should be something like:
char[][] boardArray = new char[height][width];
EDIT: Okay, now for the printing part. Your current code is:
public void displayBoard(){
for (int k=0; k < boardArray.length; k++)
for (int l=0; l < boardArray[k].length; l++){
System.out.print(boardArray[k][l]);
}
System.out.println();
}
This is equivalent to:
public void displayBoard() {
for (int k = 0; k < boardArray.length; k++) {
for (int l = 0; l < boardArray[k].length; l++) {
System.out.print(boardArray[k][l]);
}
}
System.out.println();
}
... so you're only calling println after the outer loop has finished. If you just move the call to println to after the inner loop, it'll be fine:
public void displayBoard() {
for (int k = 0; k < boardArray.length; k++) {
for (int l = 0; l < boardArray[k].length; l++) {
System.out.print(boardArray[k][l]);
}
System.out.println();
}
}
Note that this sort of thing is clearer if you always include braces for loops, if statements etc.

Runtime allocation of multidimensional array

So far I thought that the following syntax was invalid,
int B[ydim][xdim];
But today I tried and it worked! I ran it many times to make sure it did not work by chance, even valgrind didn't report any segfault or memory leak!! I am very surprised. Is it a new feature introduced in g++? I always have used 1D arrays to store matrices by indexing them with correct strides as done with A in the program below. But this new method, as with B, is so simple and elegant that I have always wanted. Is it really safe to use? See the sample program.
PS. I am compiling it with g++-4.4.3, if that matters.
#include <cstdlib>
#include <iostream>
int test(int ydim, int xdim) {
// Allocate 1D array
int *A = new int[xdim*ydim](); // with C++ new operator
// int *A = (int *) malloc(xdim*ydim * sizeof(int)); // or with C style malloc
if (A == NULL)
return EXIT_FAILURE;
// Declare a 2D array of variable size
int B[ydim][xdim];
// populate matrices A and B
for(int y = 0; y < ydim; y++) {
for(int x = 0; x < xdim; x++) {
A[y*xdim + x] = y*xdim + x;
B[y][x] = y*xdim + x;
}
}
// read out matrix A
for(int y = 0; y < ydim; y++) {
for(int x = 0; x < xdim; x++)
std::cout << A[y*xdim + x] << " ";
std::cout << std::endl;
}
std::cout << std::endl;
// read out matrix B
for(int y = 0; y < ydim; y++) {
for(int x = 0; x < xdim; x++)
std::cout << B[y][x] << " ";
std::cout << std::endl;
}
delete []A;
// free(A); // or in C style
return EXIT_SUCCESS;
}
int main() {
return test(5, 8);
}
int b[ydim][xdim] is declaring a 2-d array on the stack. new, on the other hand, allocates the array on the heap.
For any non-trivial array size, it's almost certainly better to have it on the heap, lest you run yourself out of stack space, or if you want to pass the array back to something outside the current scope.
This is a C99 'variable length array' or VLA. If they are supported by g++ too, then I believe it is an extension of the C++ standard.
Nice, aren't they?

Resources