Dynamic 2D Array Creation Runtime Error - c++

I'm trying to create a multidimentional int array with the following function code:
int ** createIntMatrix(unsigned int rows, unsigned int cols)
{
int ** matrix;
unsigned int i,j;
matrix = (int **) calloc(cols, sizeof(int *));
for(i = 0; i < cols; i++)
matrix[i] = (int *) calloc(rows, sizeof(int));
for(i = 0; i < cols; i++)
for(j = 0; j < rows; j++)
matrix[i][j] = 0;
return matrix;
}
I create three instances using this function in the following code,
cout<<"allocating temporary data holders..."<<endl;
int ** temp_meanR;
int ** temp_meanG;
int ** temp_meanB;
temp_meanR = createIntMatrix(img->height,img->width);
temp_meanG = createIntMatrix(img->height,img->width);
temp_meanB = createIntMatrix(img->height,img->width);
cout<<"....done!"<<endl;
I'm accessing these elements like temp_meanB[4][5].
But unfortunately, I get the following error during runtime:
allocating temporary data holders...
....done!
tp6(1868) malloc: *** error for object 0x122852e08: incorrect checksum for freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug
Abort trap
Where am I going wrong here?

for(i = 0; i < cols; i++)
for(j = 0; i < rows; i++)
matrix[i][j] = 0;
note the inside for loop, it says j=0; i<rows; i++ (before Aarohi Johal's edit)
Next you do not have to set the memory manually to 0, as calloc does it for you.
In C++, you should use new and delete .
In the code segment
matrix = (int **) calloc(cols, sizeof(int *));
for(i = 0; i < cols; i++)
matrix[i] = (int *) calloc(rows, sizeof(int));
I think first the rows should be allocated and then for each row link the int arrays.
Visulize like this:
+--------+
| matrix |
+--------+
| c o l s
| +----------------------------+
V | |
+-- +---+ +---+---+---+ +---+
| | |-->| | | | . . . | |
| +---+ +---+---+---+ +---+
| | |--+
r | +---+ | +---+---+---+ +---+
o | | | +-->| | | | . . . | |
w | +---+ +---+---+---+ +---+
s . .
. .
. .
| | |
| +---+ +---+---+---+ +---+
| | |-->| | | | . . . | |
+-- +---+ +---+---+---+ +---+
First do the rows and then the cols, in the above visualization, then the arr[i][j] interpretation would be like normal array.

Related

initialization of array using vector in cpp

vector< vector<int> > pairSum(vector<int> &arr, int s){
int n = arr.size();
// Used to store result.
vector< vector<int> > ans;
// Checking sum for every element.
for(int i = 0; i < n; i++) {
for(int j = i + 1; j < n; j++) {
if(arr[i] + arr[j] == s) {
vector<int> pair(2);
pair[0] = arr[i];
pair[1] = arr[j];
ans.push_back(pair);
}`enter code here`
}
}
// Used to store final sorted result.
vector<vector<int> > res(ans.size(),vector<int>(2,0));
for(int i = 0; i < ans.size(); i++) {
int a = ans[i][0], b = ans[i][1];
res[i][0] = min(a, b);
res[i][1] = max(a, b);
}
sort(res.begin(),res.end());
return}
what is the need of this line in code
vector<vector<int> > res(ans.size(),vector<int>(2,0));
what is the processing of this line
I think it will intialise new vector of type vector but I want to know on what basis and how the vector is initialised?
Let's break this into parts:
vector<vector<int>> res
Initializes a vector res, of which every element is a vector of integers
(ans.size(), vector<int>(2, 0))
To understand this part it is better to visualize vector<vector<int>> as a 2D array:
+--------------------------------------------+
| |
+---+---+ <----+ |
| 0 | 0 | | |
+---+---+ | |
| 0 | 0 | | |
+---+---+ | |
| 0 | 0 | ans.size() <---------------------------------+
+---+---+ | | |
| 0 | 0 | | | |
+---+---+ | | |
| 0 | 0 | | | |
+---+---+ <----+ | |
|-- 2 --| | |
| | |
+-------------------------------------------+ | |
| | |
vector<vector<int>> res(ans.size(), vector<int>(2, 0)) |
| |
+---------------------------+
So ans.size() is the length of the outer vector, 2 is the length of each of the inner vectors, and 0 is the value to which each element of the inner vectors will be initialized.

Comparing elapsed time to copy memory buffers: memcpy vs ForLoopIndexCopying

I am trying to understand the difference between "memcpy" and "for-loop-index-copying" of a buffer in the time it takes to copy.
results:
CopyingType | MemoryType | RunMode | Elapsed Time(ms)
-----------------------------------------------------------
memcpy | stack | Debug | x
forLoopIndexing | stack | Debug | 30x
memcpy | stack | Release | 0
forLoopIndexing | stack | Release | 0
memcpy | heap | Release | 0
forLoopIndexing | heap | Release | 2000
Here is my code to run... Maybe I am doing something wrong ???
Seems odd that to copy a 500,000 byte buffer 100,000 times takes no time at all or at least less than the resolution of the machine... in my case 16ms.
#include "stdafx.h"
#include <windows.h>
#include <iostream>
int main()
{
long baseTime;
const long packetLength = 500000;
//char packet1[packetLength];//stack
//char packet2[packetLength];//stack
char *packet1 = (char*)calloc(packetLength, sizeof(char));//heap
char *packet2 = (char*)calloc(packetLength, sizeof(char));//heap
memset(packet1, 0, packetLength);//init
memset(packet2, 0, packetLength);//init
long NumPackets = 100000;
long NumRuns = 10;
for (long k = 0; k < NumRuns; k++)
{
//create packet
printf("\npacket1:\n");
for (long i = 0; i < packetLength; i++) {
packet1[i] = (char)(i % 26 + 65);
}
printf("\nk:%d\n", k);
//index copy
baseTime = GetTickCount();
long ii = 0;
for (long j = 0; j < NumPackets; j++) {
for (long i = 0; i < packetLength; i++) {
packet2[i] = packet1[i];
}
}
printf("Time(IndexCopy): %ld\n", GetTickCount() - baseTime);
//memcpy
memset(packet2, 0, packetLength);//reset
baseTime = GetTickCount();
for (long j = 0; j < NumPackets; j++) {
memcpy(packet2, packet1, packetLength); //Changed via PaulMcKenzie.
}
printf("Time(memcpy): %ld\n", GetTickCount() - baseTime);
//printf("\npacket2\n");
for (long i = 0; i < packetLength; i++) {
//printf("%c", packet2[i]);
}
}
int iHalt;
scanf_s("%d", &iHalt);
return 0;
}
Via the change... the new table
CopyingType | MemoryType | RunMode | Elapsed Time(ms)
-----------------------------------------------------------
memcpy | stack | Debug | x
forLoopIndexing | stack | Debug | 50x
memcpy | stack | Release | 0
forLoopIndexing | stack | Release | 0
memcpy | heap | Release | 2000
forLoopIndexing | heap | Release | 2000
Maybe I am doing something wrong ???
You are doing something wrong, more to the point, in the code that uses memcpy.
const long packetLength = 500000;
char *packet1 = (char*)calloc(packetLength, sizeof(char));
char *packet2 = (char*)calloc(packetLength, sizeof(char));
//...
for (long j = 0; j < NumPackets; j++) {
memcpy(packet2, packet1, sizeof(packet2)); // <-- Incorrect
}
The sizeof(packet2) is the same as sizeof(char *), which more than likely is either 4 or 8.
What you want is not the sizeof(char *), but the actual number of bytes to copy.
for (long j = 0; j < NumPackets; j++) {
memcpy(packet2, packet1, packetLength);
}

Strange behaviour in nested For Loops

First of all, I'm pretty new to C++ so try not to be too harsh on me. I wrote this block of code:
int LargestProduct (string numStr, int groupSize) {
int numOfGroups = numStr.size() / groupSize;
int groupsRemaining = numStr.size() % groupSize;
int largestProduct = 0, thisProduct = 1;
for (int i = 1; i <= numOfGroups; i++) {
for (int j = i; j <= groupSize; j++)
thisProduct *= (numStr[j-1] - '0');
if (thisProduct > largestProduct)
largestProduct = thisProduct;
thisProduct = 1;
}
// .. A bit more irrelevant code here
return largestProduct;
}
The function call LargestProduct ("1234567890", 2) should yield 72, but it wrongly yields 6. So, for some reason, this code will work but not as expected (Note: this code I wrote should compute the largest product of groupsSize-adjacent numbers in a big, given number called numStr).
I did some debugging, and found a strange behaviour in the nested for-loop. I set up a breakpoint inside the second for-loop
thisProduct *= (numStr[j] - '0');
After some iterations (for example, 8 iterations), this is what I would expect i and j to be:
+--------+---------+
| i | j |
+--------+---------+
| 1 | 1 |
| 1 | 2 |
| 2 | 1 |
| 2 | 2 |
| 3 | 1 |
| 3 | 2 |
| 4 | 1 |
| 4 | 2 |
+--------+---------+
This is what really happens:
+--------+---------+
| i | j |
+--------+---------+
| 1 | 1 |
| 1 | 2 |
| 2 | 2 |
+--------+---------+
And suddenly the program spits out a wrong result (6, instead of 72)
But this seems counterintuitive, to say the least. The variable i goes from 0 to numOfGroups, which in the example above equals 5. On the other hand, j goes from i to groupSize, which happens to be 2.
There should be 5*2 = 10 iterations, but there are only 3 of them. Also, in the last iteration, j should be "re-initialized" to 0. This doesn't happen though.
Anyone please help this C++ newbie?
EDIT
The problem was that the j-for-loop ranged from a moving index (i) to a non-moving index(groupSize). This was causing that "shrinking" effect in the second for-loop, which is easily fixed by changing this line:
for (int j = i; j <= groupSize; j++)
To this other one:
for (int j = i; j <= i + groupSize - 1; j++)
And to make the full algorithm to work as expected, one should also replace these lines:
int numOfGroups = numStr.size() / groupSize;
int groupsRemaining = numStr.size() % groupSize;
with this single one:
int numOfGroups = numStr.size() - 1;
EDIT 2
Everything is OK now, thank you for your kindness guys! I appreciate it. The whole code is:
int LargestProduct (string numStr, int groupSize) {
int numOfGroups = numStr.size() - 1;
int largestProduct = 0, thisProduct = 1;
for (int i = 1; i <= numOfGroups; i++) {
for (int j = i; j <= i + groupSize - 1; j++)
thisProduct *= (numStr[j-1] - '0');
if (thisProduct > largestProduct)
largestProduct = thisProduct;
thisProduct = 1;
}
return largestProduct;
}
You said:
On the other hand, j goes from 0 to groupSize
But the code says:
for (int j = i; j <= groupSize; j++)
This means j is going from i to groupSize, not 0 to groupSize

Reading triple nested for loop

My code is as follows. My confusion occurs during the 2nd and 3rd loop. Why does the result return 1*** then 12** then 123* then 1234.. I get the j loop is reset to 0 but doesn't it reenter the k loop whenever its true that j<=i?
for(int i = 1; i <= 4; i++)
{
for(int j = 1; j <= i; j++)
cout << j;
for(int k = 4 - i; k >= 1; k--)
cout << "*";
cout << endl;
}
Some clarification first:
Firstly: j is never reset to 0, but to 1.
Secondly: This is imho no triple-nested for-loop, which was be (but is not needed to have your code working as you describe it):
for(...) {
for(...) {
for(...) {
}
}
}
To your confusion:
Pretty printing your code:
for(int i=1; i<=4; i++) {
// Write the digits 1..i (1, 12, 123, 1234)
for(int j=1; j<=i; j++) {
std::cout << j;
}
// Write the stars (***, **, *)
for(int k=(4-i); k>=1; k--) {
std::cout << "*";
}
std::cout << std::endl;
}
Imagine the following sequences:
// Iteration | i | j | k | String
// 1 | 1 | 1 | 3 | 1*
// 2 | 1 | 1 | 2 | 1**
// 3 | 1 | 1 | 1 | 1***\n
// 4 | 2 | 1 | - | 1
// 5 | 2 | 2 | - | 12
// 6 | 2 | 2 | 2 | 12*
// 7 | 2 | 2 | 1 | 12**\n
// 8 | 3 | 1 | - | 1
// 9 | 3 | 2 | - | 12
// 10 | 3 | 3 | - | 123
// 11 | 3 | 3 | 1 | 123*\n
// 12 | 4 | 1 | - | 1
// 13 | 4 | 2 | - | 12
// 14 | 4 | 3 | - | 123
// 15 | 4 | 4 | - | 1234\n
The k-loop is reentered, if the initial index:
// k:=(4-i) >= 1
So entering the k-Loop is exclusively dependent on the index i.
Mathematically:
// (4-i) >= 1
// <=> -i >= (1-3)
// <=> -i >= -3
// <=> i <= 3
So the k-loop is reentered, as long as i is <= 3.
In order to get the effect you want your code should be like this:
for(int i = 1; i <= 4; i++)
{
for(int j = 1; j <= i; j++)
{
cout << j;
for(int k = 4 - i; k >= 1; k--)
cout << "*";
}
cout << endl;
}
if you dont have the {} the k loop is executed only after finishing the j loop

I can't figure out a destructor for this 2D ptr array. Need suggestions

I've been thinking hard for a destructor of 2D pointer array. Any suggestions would be of great help.
The following is the structure of my array where x = int's AND * = pointers
+---+---+---+
| * | * | * |
+-|-+-|-+-|-+
| | V
| | +---+---+---+
| | | x | x | x |
| | +---+---+---+
| V
| +---+---+---+
| | x | x | x |
| +---+---+---+
V
+---+---+---+
| x | x | x |
+---+---+---+
Here is the code for my constructor:
matrix(int x, int y)
{
m = x;
n = y;
p = new(int *[m]);
for(i=0 ; i<m ; i++)
p[i] = new(int[n]);
}
~matrix()
{
for(i=0 ; i<m ; i++)
delete[] p[i];
delete[] p;
}