bad argument 1 to sizeof() error in pike - sizeof

I wrote a big program in pike, and suddenly it gives me an error it didn't give me before:
bad argument 1 to sizeof().
Does someone know the problem? what can I do? it worked before. That's the code:
int main()
{
string path;
path=Stdio.Readline()->read("enter a path");
add_module_path(path);
array fileArr=get_dir(path);
int i=0;
int j=0;
while (j != sizeof(fileArr))
{
// ...
}
}

if the given path does not exist, then get_dir() will return 0.
0 is an invalid argument to sizeof().
check the relevant values before passing them on.
the simplest in this case:
while (arrayp(fileArr) && j != sizeof(fileArr))
you could also stat() the path before passing it to get_dir()

Related

How would I print the index of an array? C++

I was just wondering how do I print off the Index position of an array? I know there's an if loop involved but I just can't seem to understand it properly.
I want the code to be able to print off what the element of the Array is and the position number. I should also mention that this is for a function as well. Any help will be appreciated. Below is my code
int index_of(string names[], int size)
{
string name;
int index;
for(int i = 0; i < size; i++)
{
if (to_lowercase (names[i]) == to_lowercase(name));
{
return;
}
}
}
What you are trying to do is called "searching".
You have a string which (potentially) is the known content of an entry in an array, but at an unknown index.
What you need to do is to find the index which, used for accessing the entry at that index, yields content which is identical to what you are looking for.
The code you show is more or less pseudo code for doing exactly that.
However, the shown code will not work for the following reasons:
it does not correctly return the index in question, it should return i;
it only returns explicitly in case of finding something, it should, after the loop, return -1;(as a proposal how to communicate failure)
it incorrectly compares (the == operator cannot meaningfully be used on "strings", which in C are only pointers to characters), it should use strncmp(), see e.g. https://en.cppreference.com/w/c/string/byte/strncmp
it does not actually print anything, but I think that is a problem of phrasing your goal and you can easily add a print outside of the shown code, using the (now hopefully correct and correctly returned) return value of the shown function
it has the problem mentioned by Nathan Pierson, see their comment/answer
This is what managed to print the indexes, you guys were actually able to help me understand what I was doing
int index_of(string names[], int size, string name)
{
for(int i = 0; i < size; i++)
{
if (to_lowercase (names[i]) == to_lowercase(name));
{
return i;
}
return -1;
}
}

How do I fix this runtime error related to div by zero?

Here is the chunk of code in question that I've pulled from my program:
#include <vector>
using namespace std;
vector<double> permittingConstructionCosts(56);
static const int PERMITTING_PERIODS = 0;
static const int CONSTRUCTION_PERIODS = 11;
static const double CONSTRUCTION_COSTS = 2169506;
static const double PERMITTING_COSTS = 142085;
static const int PERMITTING_CONSTRUCTION_PERIODS = PERMITTING_PERIODS + CONSTRUCTION_PERIODS;
void calcExpenses // Calculates permitting and construction expenses
(
vector<double>& expense,
double value1,
double value2
)
{
int i;
for (i=0; i<=PERMITTING_PERIODS + 1; i++)
{
expense[i] = value1;
}
for (i=PERMITTING_PERIODS + 2; i<expense.size(); i++)
{
if (i < PERMITTING_CONSTRUCTION_PERIODS + 2)
{
expense[i] = value2;
}
}
}
int main()
{
if (PERMITTING_PERIODS != 0)
{
calcExpenses(permittingConstructionCosts, -PERMITTING_COSTS/PERMITTING_PERIODS, -CONSTRUCTION_COSTS/CONSTRUCTION_PERIODS);
}
else
{
calcExpenses(permittingConstructionCosts, 0, -CONSTRUCTION_COSTS/CONSTRUCTION_PERIODS);
}
return 0;
}
According to ideone (http://ideone.com/LpzUny) the code has a runtime error that returns "time: 0 memory: 3456 signal:11".
I've tried to look for solutions on SO and found the following links:
How can I avoid a warning about division-by-zero in this template code?
How to eliminate "divide by 0" error in template code
However, I don't know how to use templates because I am new to c++ and I'm not sure I need to use them in this case so I have no clue how to adapt those solutions to my particular problem if it's even possible.
I'm pretty sure that the "-PERMITTING_COSTS/PERMITTING_PERIODS" is causing the problem but I thought that simply checking the divisor would solve the problem. This function seems to work for every other value other than 0 but I need to account for the case where PERMITTING_PERIODS = 0 somehow.
I would very much appreciate any help I can get. Thanks in advance!
Edit: I actually do initialize the vector in my program but I forgot to put that in because the size is decided elsewhere in the program. The chunk of code works once I fix that part by putting in a number but my program still has a runtime error when I set PERMITTING_PERIODS to 0 so I guess I have to go bug hunting elsewhere. Thanks for the help!
The problem lies inside the function, which is called by the else statement in the main function:
for (i=0; i<=PERMITTING_PERIODS + 1; i++)
{
expense[i] = value1;
}
Here, PERMITTING_PERIODS is 0, thus you loop from 0 to 2 (inclusive).
However, expense.size() is 0, since your vector is empty. As a result, you are trying to access an empty vector, which causes a segmentation fault.
With that said, print the value of i inside the loop, you should see that you try to access expense[0], but the vector is empty, so it has no first slot (basically it doesn't have any)!!
So replace that with:
expense.push_back(value1);
which will allocate enough space for your values to be pushed into the vector.
The answer given in the cited links, (i.e. "How to eliminate "divide by 0" error in template code") applies equally well here. The other answers were given in the context of templates, but this is completely irrelevant. The sample principle applies equally well with non-template code, too. The key principle is to compute a division, but if the denominator is zero, you want to compute the value of zero instead of the division.
So we want to compute -PERMITTING_COSTS/PERMITTING_PERIODS, but use the value of 0 instead of the division when PERMITTING_PERIODS is 0. Fine:
int main()
{
calcExpenses(permittingConstructionCosts,
(PERMITTING_PERIODS == 0 ? 0: -PERMITTING_COSTS)/
(PERMITTING_PERIODS == 0 ? 1: PERMITTING_PERIODS),
-CONSTRUCTION_COSTS/CONSTRUCTION_PERIODS);
return 0;
}

Having trouble passing array to recursive function c++

When I run the function "check_row" within itself, there is a problem with the way I'm trying to pass in the array "sudoku_temp", but I'm not sure what I'm doing wrong. Am I missing something?
int check_row(int j_position, int generated_value, int sudoku_temp[][9]){
for (int i_position = 0; i_position < 9; i_position++)
{
if (generated_value == sudoku_temp[i_position][j_position])
{
generated_value = generate_number();
check_row(j_position, generated_value, sudoku_temp[][j_position]);
}
else
return generated_value;
}
}
To clarify, the problem is when I try to call on the function within itself. Thanks.
When you want to extract a value from an array, you cannot leave empty brackets like you did. On the other hand, the function prototype looks similar and it's perfectly fine. Why?
int sudoku_temp[][9] // A 2D array of integers second dimension of which is of size 9
Or in other words, an array (of unknown size) of arrays of size 9. We are not telling the compiler how big the array really is and we don't have to in this case as it is simply given to us as an argument.
When accessing elements on the other hand, we cannot leave empty brackets for a simple reason: we want to access an element and the compiler has to know which one. Cutting to the chase - removing the empty [] should solve your problem.
use a variable instead of fixed length like 9. since in recursion the argument may be different.
int check_row(int j_position, int generated_value, int sudoku_temp[][n])
{
for (int i_position = 0; i_position < n; i_position++)
{
if (generated_value == sudoku_temp[i_position][j_position])
{
generated_value = generate_number();
check_row(j_position, generated_value, sudoku_temp[][j_position]);
}
else
return generated_value;
}
}

C++ vector memory access issue

I have a vector with a list of commands as shown below:
//COMMAND INITIALISATION
std::vector<std::string> objectInitialisationAction;
objectInitialisationAction.push_back("CREATE"); //0
objectInitialisationAction.push_back("END_CREATE"); //1
objectInitialisationAction.push_back("START_TIMELINE"); //2
I only access this vector by using my function shown below:
int SearchFor(std::string search, std::vector<std::string> from)
{
int result=-1;
for(int i=0; i<from.size(); i++)
if(from[i]==search)
{
result=i;
break;
}
if(result == -1)
{
std::ofstream error("searching.txt");
error<<"search failed, original value = \""<<search<<"\""<<std::endl;
error<<"values in the table:"<<std::endl;
for(int i=0; i<from.size();i++)
error<<"value "<<i<<": "<<from[i]<<std::endl;
error.close();
}
return result;
}
With only one function call:
commandNum=SearchFor(command[0], objectInitialisationAction);
This is the only place where I access the vector, yet when I call the function for the nth time (it always brakes at the same point in the code) it accesses wrong and outputs gibberish. Some of the code I list below:
search failed, original value = "CREATE"
values in the table:
value 0: CREATE Øç¼ Œ Ôç¼ Œ Ðç¼ Exit ¼ç¼ ¸ç¼ Œ  p«üxðù ; ´ç¼ Œ pëù#òø €< °ç¼ ŒBerlin Sans FB Demi e ¬ç¼ ˆ°¿^nmra œç¼ ŒBerlin Sans FB Demi e ˜ç¼ help ”ç¼ ˆ  object_dump ç¼ test Œç¼ Ž spawn ˆç¼ ‹ load_map „ç¼ Ž
//and so on...
Any suggestions as to why a vector may corrupt like that?
It seems all correct. Compile and execute this. If it is all correct probably the problem is in another part of your code.
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
int SearchFor(std::string search, std::vector<std::string> from)
{
int result=-1;
for(unsigned int i=0; i<from.size(); i++)
if(from[i]==search)
{
result=i;
break;
}
if(result == -1)
{
std::ofstream error("searching.txt");
error<<"search failed, original value = \""<<search<<"\""<<std::endl;
error<<"values in the table:"<<std::endl;
for(unsigned int i=0; i<from.size(); i++)
error<<"value "<<i<<": "<<from[i]<<std::endl;
error.close();
}
return result;
}
int main()
{
std::vector<std::string> objectInitialisationAction;
objectInitialisationAction.push_back("CREATE"); //0
objectInitialisationAction.push_back("END_CREATE"); //1
objectInitialisationAction.push_back("START_TIMELINE"); //2
for(unsigned int i=0; i<objectInitialisationAction.size(); i++)
{
cout<< objectInitialisationAction[i] << endl;
}
cout << "FOUND " << SearchFor("CREATE", objectInitialisationAction);
return 0;
}
I suggest you to add using namespace std; at the beginning of the file, so you have not to add std::blablabla on each declaration...your code will be more readable :) and please....INDENT IT :)
Your code looks correct to me. In this case, there should be another part of your application that corrupts the memory. For example, there could be an out-of-range array access, a dangling pointer or a use-after-delete somewhere. Tools like Valgrind might help you here.
The code looks ok as it is. The most likely scenario for me is that the length field of your strings gets unintentionally overwritten, because the command, i.e. the actual data, is still there. It's just that the string thinks it's longer than that. (Overwriting the characters wouldn't lead to the output you report: The commands would be overwritten, but the string length would still be short.) Overwriting memory typically happens through an array index or pointer which is out of bounds. The data it points to must have the same linkage as the strings (in your example local or global/static).
One strategy for bug searching would be to occasionally print the length of objectInitialisationAction's element strings; if they are too long you know something went wrong.
It may help to comment out code using a kind of binary search strategy (comment out one half -- mocking it's functionality to keep the prog running -- and look whether the error still occurs, then divide the faulty part again etc.).
Note that you pass the vector by value into SearchFor() which is perhaps unintended. The corruption may happen at the caller's or callee's side which should be easy to test.--
Hoped that helped.
try to pass all params through const refs:
int SearchFor(const std::string& search, const std::vector<std::string>& from)
{
...
}

C++ program to compute lcm of numbers between 1 to 20 (project euler )

as the title explains this is a program to find lcm of numbers between 1 to 20. i found an algorithm to do this, here's the link
http://www.cut-the-knot.org/Curriculum/Arithmetic/LCM.shtml
there is a java applet on the webpage that might explain the algorithm better
Problem: i wrote the code compiler shows no error but when i run the code the program goes berserk, i guess may be some infinite loopig but i can't figure it out for the life of me. i use turbo c++ 4.5 so basically if anyone can look at the code and help me out it would be great . thanks in advance
Algorithm:
say we need to find lcm of 2,6,8
first we find the least of the series and add to it the number above it, i.e the series become
4,6,8
now we find the least value again and add to it the intitial value in the column i.e 2
6,6,8
so the next iteration becomes
8,6,8
8,12,8
10,12,8
10,12,16
12,12,16
14,12,16
14,18,16
16,18,16
18,18,16
18,18,24
20,18,24
20,24,24
22,24,24
24,24,24
as you can see at one point all numbers become equal which is our lcm
#include<iostream.h>
/*function to check if all the elements of an array are equal*/
int equl(int a[20], int n)
{
int i=0;
while(n==1&&i<20)
{
if (a[i]==a[i+1])
n=1;
else
n=0;
i++;
}
return n;
}
/*function to calculate lcm and return that value to main function*/
int lcm()
{
int i,k,j,check=1,a[20],b[20];
/*loading both arrays with numbers from 1 to 20*/
for(i=0;i<20;i++)
{
a[i]=i+1;
b[i]=i+1;
}
check= equl(a,1);
/*actual implementation of the algorith*/
while(check==0)
{
k=a[0]; /*looks for the least value in the array*/
for(i=0;i<20;i++)
{
if(a[i+1]<k)
{
k=a[i+1]; /*find the least value*/
j=i+1; /*mark the position in array */
}
else
continue;
}
a[j]=k+b[j]; /*adding the least value with its corresponding number*/
check= equl(a,1);
}
return (a[0]);
/*at this point all numbers in the array must be same thus any value gives us the lcm*/
}
void main()
{
int l;
l=lcm();
cout<<l;
}
In this line:
a[j]=k+b[j];
You use j but it is unitialized so it's some huge value and you are outside of the array bounds and thus you get a segmentation fault.
You also have some weird things going on in your code. void main() and you use cout without either saying std::cout or using namespace std; or something similar. An odd practice.
Also don't you think you should pass the arrays as arguments if you're going to make lcm() a function? That is int lcm(int a[], int b[]);.
You might look into using a debugger also and improving your coding practices. I found this error within 30 seconds of pasting your code into the compiler with the help of the debugger.
Your loop condition is:
while(n==1&&i<20)
So your equl function will never return 1 because if n happens to be 1 then the loop will just keep going and never return a 1.
However, your program still does not appear to return the correct result. You can split the piece of your code that finds the minimum element and replace it with this for cleanliness:
int least(int a[], int size){
int minPos = 0;
for(int i=0; i<size ;i++){
if (a[i] < a[minPos] ){
minPos = i;
}
}
return minPos;
}
Then you can call it by saying j = least(a, 20);. I will leave further work on your program to you. Consider calling your variables something meaningful instead of i,j,k,a,b.
Your equl function is using array indices from 0-20, but the arrays only have 1-19
j in lcm() is uninitialized if the first element is the smallest. It should be set to 0 at the top of the while loop
In the following code, when i=19, you are accessing a[20], which is out of the bounds of the array. Should be for(i=0;i<19;i++)
for(i=0;i<20;i++) {
if(a[i+1]<k)
You are not actually using the std namespace for the cout. this should be std::cout<<l
Your are including iostream.h. The standard is iostream without the .h, this may not work on such an old compiler tho
instead of hard-coding 20 everywhere, you should use a #define. This is not an error, just a style thing.
The following code does nothing. This is the default behavior
else
continue;