array of pointers in C++ and what is "BUS ERROR" [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
#include<cstdio>
#include<string>
#include<iostream>
using namespace std;
int main()
{
int a[]={0,1,2,3};
int *r[]={NULL};
for(int i=0;i<4;i++)
{
r[i]=&a[i];
cout << &a[i] << endl;
cout << a[i]<<endl;
}
for(int i=0;i<4;i++)
{
cout << r[i] << endl;
cout << *r[i] << endl;
}
return 0;
}
I have started working on the array of pointers very recently. Can someone please help me out in finding the mistake in the above program..
I attached the screenshots of the results when run on windows and linux platforms.
On Windows,the addresses of the *r[] and a[] are matching and still the values are not matching.
On linux,it says "BUS ERROR" sometimes and "Segmentation fault" sometimes.
It would be better if someone explain what the "BUS ERROR" mean? And why does it come for this program.

Your array r only has space for a single element in it, but you store 4. That overwrites memory, causing the crash.
Change this:
int *r[]={NULL};
to:
int *r[sizeof a / sizeof *a];
This makes r have the same number of elements as a, in other words 4.

int *r[]={NULL}; should be int *r[]={0, 0, 0, 0};
That will allocates space for four pointers that your following code need.
BUS ERROR: What is a bus error?

Your are not allocating enough space for your r. Try int *r[4]; and you will not get a segmentation fault.
int *r[] = {0} it's equivalent with int *r[1];

r is an array of pointers, but in your code, it has only one element. You are lucky to run it on windows but it's a undefined behavior. It might seem to work today, on your compiler, but it is not legal C or C++, and there is no guarantee that it'll still work the next time you run the program. Or that it hasn't overwritten essential data even now, and you just haven't encountered the problems that is going to cause yet.

Related

Why does my dynamic array work without being resized? [duplicate]

This question already has answers here:
No out of bounds error
(7 answers)
Closed 1 year ago.
I'm working on dynamic arrays for my c++ course, but I'm confused about the behavior of my dynamic arrays. For example, if I run this code:
int* myDynamicArr = new int[3];
for (int i = 0; i < 10; i++)
{
myDynamicArr[i] = i + 1;
cout << myDynamicArr[i] << endl;
}
I would expect it to not work since I only declared it as size 3. But when I run it, it prints out 0-9. Same thing if I do this:
char* myCharArr = new char[2];
strcpy(myCharArr, "ThisIsALongString");
cout << myCharArr;
It prints the full string even though it seems like it should fail. Can anyone explain what I'm doing wrong here? Thanks!
C++ does not perform bounds checking on arrays. So when you read or write past the bounds of an array you trigger undefined behavior.
With undefined behavior, your program may crash, it may output strange results, or it may (as in your case) appear to work properly.
Just because it could crash doesn't mean it will.

Recursive binary search - C++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
first post here so be gentle. I'm trying execute a recursive binary search. I have tried different variations of code to try to make the function work but i still doesnt.
Here's my code:
bool contained(int x, const int* pBegin, const int* pEnd){
if(x==*pBegin) { //
return pBegin;
}
int size = pEnd - pBegin; //size of the array
int mid= size/2; //the middle of the array
int const* pMid = pBegin + mid; //The address of the element in the middle of the array
if(x>*pMid) //Condition that looks if x is to the left of the array
return contained(x,pMid,pEnd);
else if(x<*pMid) //Condition that looks if x is to the right of the array
return contained(x,pBegin,pMid-1);
}
int main()
{
cout << "Binary search, test: " << endl;
int arr[] = {1,2,3,4,5,7,8,9};
int size = 9;
for(int i=0; i<size; i+=1)
arr[i] = i;
bool find = containedInSortedarray(6, &arr[0], &arr[size]);
cout << "Found " << find << endl;
}
For example here, when i execute my bool-contained function with a premade array and let it search for the value 6, it should eventually come to the conclusion that the element does not exist, yet my output says it does. Have i missed something in my code?
Thanks in advance!
There are a couple of issues with your code:
You never return false.
You return pBegin which is not a bool, (sadly in your case) it is implicitly convertible to one, but not in the way you want it too. Turn on your compiler warnings all the way up - -Wextra -Wall -pedantic -Werror should be the bare minimum, especially if you are a beginner.
Be precise about the interval your function searches in. func(x,a,b) - does it include b? Based on contained(x,pBegin,pMid-1); it seems it does, but in the case of containedInSortedarray(6, &arr[0], &arr[size]); hopefully not.
Dereferencing &arr[size] is UB.
What is the purpose of the for loop in main?
Having the size detached from the array is a disaster waiting to happen. At least use sizeof(arr)/sizeof(arr[0]). Better yet, use std::array or a std::vector.
I would suggest searching [a,b) because it can be easily be divided into [a,mid), [mid,end). That way your mid computation is already correct. You can then call it like containedInSortedarray(x,arr,arr+arr_size)
The base condition should catch the arrays of size 0 and 1 - both can be trivially tested for presence of x.

Crashing Pointer Array C++ [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Code::Blocks, Win7, C++
Hi, I'm creating an overview project for myself, and an integral part includes doing an Exchange Sort in descending order. I've created a simple trial run to test the concept.
Embarrassingly enough, I can't get past creating the array without the project crashing. This only happens when I create the array with pointers (My project's arrays are pointers, which is why I need this to work). The code compiles fine, but when I run it, I get a Window's notification that "ArrayTest.exe has stopped working"
When I print out each dereferenced value, I get:
"The original order: 1 13 5 7 2 "
When I print out each value's address, I get:
"The original order: 0x28ff08 0x28ffc4 0x760c8cd5 0x6aadab61 0xfffffffe "
The last address showed up when using an array length of 6, and crashes as well. Am I blind to a simple error in my code, or is this a hardware issue?
//filename ArrayTest
#include <iostream>
using namespace std;
int main()
{
int *j[5];
(*j)[0] = 1;
(*j)[1] = 13;
(*j)[2] = 5;
(*j)[3] = 7;
(*j)[4] = 2;
cout << "The original order: ";
for (int i = 0; i < 5; i++)
{
cout << (*j)[i] << " ";
}
return 0;
}
Consider int *j[5]; carefully. This is an array of pointers.
Those pointers are not pointing to memory that you own.
So the behaviour on dereferencing them is undefined.
Trivial fix: use int j[5]; instead, and j[0] = 1 etc.
When analysing code problems consider these numbers as approximating the probability of the error location:
99.0% - your code
0.9% - the standard library
0.09% - the compiler
0.009% - the operating system
0.001% - the hardware
If you want a pointer on array, you have to use this syntax
int array[5];
int (*j)[5] = &array;
(*j)[0] = 42;
So, firstly, the correct syntax is int j[5]; but that's C, not C++.
use std::array - actual C++ and with compile-time checking.
You're allocating an array of 5 pointers to int, not an array of 5 integers. Try to init the array like this: int j[5];
Your code writes your values 1, 13, 5, 7, 2 to the dereferenced pointers in your pointer array. Since they are uninitialized, they contain garbage and thus you're writing to random addresses in memory, which leads to the crash.

Passing pointer to function changes data and crashes program [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am new to c++, but not to OOP. This crash confuses me so much.
This is a piece of my main. This code works. It prints what I want it to print.
int _tmain(int argc, _TCHAR* argv[]) {
Weapon* wp = createWeapon();
cout <<wp->name << " " << wp->maxAttack << " " << wp->minAttack; //<<---Works fine
}
But. The following code, only passing it through a function to do the same thing, crashes. And I have no idea why. I have tryed anything I could think of, but upon entering the new function, something changes the data and it crashes.
void showWeaponInfo(Weapon* w) {
cout << "Weapon: " << w->name << "\n"; //Wont work!??!
}
int _tmain(int argc, _TCHAR* argv[]) {
Weapon* wp = createWeapon();
showWeaponInfo(wp);
}
I have debugged, and that shows that upon entering the new function, the data in "wp" changes. The following links are images of the debugging.
Am I doing something wrong? Has someone else encountered this problem? Do you have to think of something special when passing pointers as arguments?
In VC++ the debugger sets the values of unassigned variables to 204 per byte or as in your case - 0xCCCCCCCC
This means that your createWeapon() returns uninitialized pointer.
You don't show us your createWeapon(). But I guess the createWeapon() returns the pointer of local variable. Is your function like this?
Weapon* createWeapon()
{
Weapon wp(/*blabla*/);
// ...
return &wp;
}
If so, you've encountered undefined behavior.
On the end of createWeapon(), the wp variable, local variable of createWeapon(), is destroyed. Therefore, the returned pointer points to "destroyed" object. If you try to dereference that pointer, the program falls in undefined behavior, which means nobody knows what would be happened.
However, directly after calling createWeapon(), the wp variable might be alive - since the stack frame is not touched yet. That's why your first example seems to work. But in your second example, you call showWeaponInfo(), and the calling change the stack frame.

Strange GCC optimisation bug [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I'm writing a fairly large application containing many different modules. I've always been programming with the GCC debugging info turned on and all optimisations turned off, for obvious reasons of debugging. Now I've decided that it's time for a release and I've set GCC to optimise to the best of it's abilities (-O3). And this is when the strangest of bugs appeared. Take the following code:
void SomeClass::setValue(int i) { this->iValue = i; }
int SomeClass::getValue() const { return this->iValue; }
Now without optimisations, these work perfectly. With optimisations, the value of SomeClass.iValue is not modified in the setValue() method. In fact, the output of the following:
cout << x.getValue();
x.setValue(5);
cout << x.getValue();
returns
0
0
when the iValue is intialised in the class to 0.
Now the strange part: if I insert the following code into setValue():
void SomeClass::setValue(int i) { cout << "Narf"; this->iValue = i; }
the code works!
Can someone please explain to me what is going on?
did you try checking cout<<x.iValue; ? perhaps the problem is in SomeClass::getValue(); for example, it returning void or being const ? :)
also, just an idea, the optimisation might happen in cout not your actual code as hinted by cout << "Narf";
Firstly, your code is not exactly correct. Getter function should return int instead of void. I think you just typed it incorrectly here, because gcc will not let you compile that (std::cout has no overloaded operator << for type void). What is more, SomeClass.i_value doesn't compile either. Did you mean this->i_value or just i_value?