Why am I getting this writing access violation error? [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 4 months ago.
Improve this question
I'm not sure why this is happening. Updated my original post to add in the suggestions made thank you everyone for your help!
The issue function was made by my professor. The function I am making is the board() function.
MY FUNCTION
TourBus& TourBus::board()
{
char passName[40];
int i = 0;
cout << "Boarding " << busSizeNumber << " Passengers: " << endl;
for (i = 0; i < busSizeNumber; i++)
{
cout << i + 1 << "/4- Passenger Name: ";
cin.getline(passName, 40,'\n');
ticket->issue(passName);
}
return *this;
}
MY PROFESSOR'S FUNCTION
TourTicket& TourTicket::issue(const char* passengerName) {
if (passengerName && passengerName[0]) {
copyName(passengerName);
m_ticketNumber = next_ticketNumber++;
}
return *this;
}
void TourTicket::copyName(const char* str) {
int i = 0;
for (i = 0; i < 40 && str[i]; m_name[i] = str[i], i++);
m_name[i] = 0;
}
This is a picture of the instructions for this function:
this is the picture of the error
the variables i am watching are all holding the string correctly however its just not copying it and throwing that error

In this line, the method declares a pointer but doesn't initialize it to point to anything:
char* passName;
... and then in this line you call getline() and pass in the uninitialized pointer as an argument:
cin.getline(passName, 20,'\n');
getline() will try to write some text into the buffer that passName is pointing to... but passName is uninitialized, so it is not pointing to any well-defined region of memory. Hence, the attempt to dereference it invokes undefined behavior, and you get a write-access error.
I think you'd get a result more in line with what you wanted if you changed the passName declaration to something like this:
char passName[20]; // allocates 20 bytes of stack space to hold chars in

Related

bool vs void vs print or std::cout [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
What is the difference between having a void or a bool and why is the answer not displaying right? The more I look up and try to understand the deeper I dig myself into a whole. (eg: std::boolalpha)?!?
#include <iostream>
#include <stdio.h>
#include <vector>
bool findPair(int* arr, int arrLength, int k)
{
for(int i=0; i<arrLength; i++)
{
for(int j = i+1;j<arrLength; j++)
{
if(arr[i] + arr[j] == k)
{
printf("Pair Found (%d, %d)", arr[i], arr[j], "\n");
//return;
}
}
}
printf("Pair NOT Found!");
//return false;
}
int main()
{
int array[5] = {4,5,1,7,2};
int sum = 221;
int arrLength = sizeof(array)/sizeof(array[0]);
findPair(array, arrLength, sum);
std::cout << std::endl << findPair() << std::endl;
// return 0;
}
Gives the following output when a pair is found (int sum = 3;):
Pair Found (1, 2)Pair NOT Found!
1
And this output when the pair is not found (int sum = 221;):
Pair NOT Found!
1
Right now, you've told the compiler that findPair returns a bool, but the method doesn't actually return true or false. You've lied to the compiler, and the compiler is allowed to do whatever it wants in this case. A function with a return type should always have a return statement that tells the compiler what value to return to the caller (or throw an exception).
A method with a void return type does not have to have a return; statement, and it's return; statements do not have to return a value, but you can still use return; statements to tell the computer to stop executing the method and return to the caller.
In your case, since you've eliminated the return statement after "Pair Found (%d, %d)", the method keeps executing, until it reaches the end of the loop, which is why you see both printf statements execute. Make sure to put a return type there.
Separately, std::cout << findPair will try print the address of the function, but since there's no overload for that, it will convert the pointer to a boolean, thus printing 1. What you probably wanted was to store the returned value into a bool variable, and send that to cout?
If you want to output true or false instead of 1 or 0 for bool types, then stream out std::boolalpha first, as in std::cout << std::boolalpha << myBoolean;

Return char* from function on another library [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm having troubles dealing with pointer when it comes to using another library function
The library has a void function where it modifies a long value by reference successfully, but when trying to modify the value of a char*, the memory allocation from the library gets lost when the function ends, leaving me with unable to read memory.
I don't know what the size of the char* the function will create, so I can't allocate memory before it.
Any help?
EDIT1: posting some code example
EDIT2: posted 2 solutions
Main program:
char* resizedPixels = new char[2]; // random number to initialize it
long pixelsSizeRed;
//calling the method from another library
ImageResizer::reziseImg("C:\img.jpg", &resizedPixels, pixelsSizeRef);
// end of main program
on the library side, the function is as follows:
void resizeImg(char* inputPath, char** resizedPixels, long &pixelsSize){
pixelsSize=100; //calculated with other methods, hands out the value correctly
//now that I have the size, allocate memory on the char array I need
*resizedPixels = new char[pixelsSize];
//modify inputPath bytes, and passing them to resizedPixels
char* buffer = "something manipulated";
for (int i = 0; i < pixelsSize; ++i) {
(*resizedPixels)[i] = buffer[i];
}
}
Solution 2: using vectors
void resizeImg(vector<char>&, long );
int main() {
vector<char> pixelVec;
char* resizedPixels;
long pixelsSizeRef;
resizeImg(pixelVec, pixelsSizeRef);
// for loop to pass value
resizedPixels=new char[pixelsSizeRef];
for(int i=0; i<pixelsSizeRef; i++){
resizedPixels[i]=pixelVec.at(i);
}
//our char* has the values from library's function
return 0;
}
void resizeImg(vector<char> &myVec, long pixelSize) {
// modify your string
pixelSize=10;
char foo[pixelSize] = "abcdefghi";
for (int i = 0; i < 10; ++i) {
myVec.push_back(foo[i]);
}
}
The reason the value is lost is because you try to modify a pointer in a function by passing it by value (you pass a char*). You need to pass it by pointer (so a char**) if you want to modify it within the function and have that modification reflected outside of it.
Think about it the same way you would think about a function which is supposed to modify an int. You would need to pass a pointer on the integer (a int*) for the modification to be reflected outside the function. Here, you pass your char* by value, so that in the function, there is a different object of type char* that is constructed, and on which all your manipulation are done. Once you exit the function, that object on which everything has been done is destructed, and you never actually touched the object in the caller block that you wanted to modify in the first place.
I wrote a minimal functioning code of a function that modify a char* which you can use as an example if you want to modify accordingly your code (put it in a .cpp file and run it) :
#include <iostream>
void resizeImg(char** myarray);
int main() {
char* resizedPixels;
resizedPixels = new char[5];
for (int i = 0; i < 4; ++i) {
resizedPixels[i] = i + 65;
}
resizedPixels[4] = '\0';
std::cout << resizedPixels << std::endl;
resizeImg(&resizedPixels);
std::cout << resizedPixels << std::endl;
return 0;
}
void resizeImg(char** myarray) {
// allocate memory for your string
// (you can do that with your pixelSize,
// don't forget that the last char is '\0')
*myarray = new char[10];
// modify your string
char foo[10] = "abcdefghi";
for (int i = 0; i < 10; ++i) {
(*myarray)[i] = foo[i];
}
}
The output is :
ABCD
abcdefghi
Here, the char* is passed by pointer, so that the prototype of the function takes a char**. And it actually modifies the string from the caller block.

get error while trying to access a list [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 5 years ago.
Improve this question
I've got a list with a struct:
struct structPlacedBets
{
int betOption = 0;
int betValue = 0;
int betChips = 0;
int player = 1;
}
the list:
list <structPlacedBets> placedBets;
when writing to the list, there is no problem. I fill a temporary variable with the data, and then I handover the temporary variable to the list.
placedBets.push_back (tempPlacedBets);
Everything fine.
I also can access the list in the main function, everything good.
But, I wanted to handover the memory adress from the list to a function, and then output everything from the list. In the moment where I try to access the data, my program crashes.
Here is the code:
struct structPlacedBets
{
int betOption = 0;
int betValue = 0;
int betChips = 0;
int player = 1;
}
list <structPlacedBets> placedBets;
structPlacedBets tempPlacedBets; //temporary variable for filling the list
.
.
.
placedBets.push_back (tempPlacedBets);
.
.
.
void outputList(list <structPlacedBets> &tempList)
{
list <structPlacedBets>::iterator Iterator;
for (Iterator == tempList.begin(); Iterator != tempList.end(); Iterator++)
{
cout << Iterator->betOption; //here the program crashes
}
}
int main()
outputList(placedBets);
return 0;
When accessing the list directly in the main, without another function, everything is fine.
Works well:
int main()
list <structPlacedBets>::iterator Iterator;
for (Iterator = placedBets.begin(); Iterator != placedBets.end(); Iterator++)
{
cout << (*Iterator).betOption << endl;
cout << (*Iterator).betValue << endl;
cout << (*Iterator).betChips << endl;
cout << (*Iterator).player << endl;
}
Hope, anybody knows the problem and the answer.
Thank you.
In the first example, you have a typo:
for (Iterator == tempList.begin(); Iterator != tempList.end(); Iterator++)
// ^^
Iterator was never initialised to anything! Comparing it, then dereferencing it (and, if you got that far, incrementing and comparing it again) all has undefined behaviour.
In the second example you correctly wrote =.
Pay closer attention to your code, and turn on your compiler's warnings.

Updating an array using a function 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 8 years ago.
Improve this question
I'm having a very nooby problem.
void update(node city, int costpath) {
int i;
for (i = 1; i < city.concity.size(); i++) {
city.costcity[i] = city.costcity[i] + costpath;
}
// Updates the sorrounding paths with the cost path of the previous one
}
node is a struct. It has vectors concity and costcity. When I call this function to update the values in the main, it doesn't work! When I print it out, it still shows the same old values…
Two problems:
void update(node city, int costpath) {
// ^^^^ 1) You're taking your node by-value. So it's a copy
// Internal to this function, you're just modifying the local city
int i;
for (i=1;i<city.concity.size();i++) {
// ^^^ 2) C++ is zero-indexed, so this loop skips the first element
The correct implementation would be:
void update(node& city, int costpath) {
for (int i = 0; i < city.concity.size(); ++i) {
city.costcity[i] += costpath;
}
}
C and C++ pass parameter by value when call function.
void update(node* city, int costpath) {
int i;
for (i=1;i<city->concity.size();i++) {
city->costcity[i] = city->costcity[i] + costpath;
}
}
See http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_value
and http://clc-wiki.net/wiki/C_language:Terms:Pass_by_value
pass node city as a pointer or reference to the function.
c++ is 0 indexed thus start with 0 and increment till the array size.
void update(node& city, int costpath) {
or
void update(node* city, int costpath) {
and
for (int i = 0; i < city.concity.size(); ++i) {

pointer to array and then getting full array c++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
EDIT (Remake): Here's what I'm trying to do:
char* someArray = new char[someIntVariable];
And then loop over the array and use a custom function to get the contents of the other array (that's where the problem lies):
char* temp = someFunc(someArray, someIntVariable); //someFunc is a char* returning function
for(int i = 0; i < someIntVariable; i++){
someArray[i] = temp[i] //temp[i] is where the problem lies. It returns something like: /213
}
Text version: I'm trying to get a pointer to a char array to return all of the arrays contents (only using one single pointer) and loop over a previously created array and fill it's spaces or somehow assign it one single assignment.
Hope this is comprehensible.
"someFunc":
char* convertCharArr(char* _inputArr, int arrSize){
char *inputArr = new char[arrSize];
std::memmove(inputArr, _inputArr, sizeof(*inputArr));
static char *resizedUsrInptAns = new char[arrSize];
for(int i = 0; i < sizeof(inputArr)/sizeof(inputArr[0]); i++){
if(i == arrSize + 1){
break;
}
resizedUsrInptAns[i] = inputArr[i];
}
return resizedUsrInptAns;
}
ptr2 and ptr1 are equivalent, so I am going to ignore ptr2 for my answer.
If you want to clone a char array of unknown size, you have to use dynamic memory allocation:
char * p = malloc(strlen(ptr1) + 1);
strcpy(p, ptr1);
// ...
free(p);
You can't assign a pointer to an array, thats impossible in c. You can only do the opposite, assigning an array to a pointer.
You will have to create a new array(with dynamic allocation) and copy the data into that array.
Example
char* pChar = GetArrayPointer();
char* pNewArrayPointer = (char*)malloc(strlen(pChar) + 1);
strcpy(pNewArrayPointer, pChar);
Edit
1) You don't have to copy _inputArr because you don't write data to it in converCharArr().
2) Why are you using sizeof(inputArr)/sizeof(inputArr[0]), it doesn't works, because inputArr is a pointer(well, there are some differences between pointers and arrays :)). You should use arrSize.
Array and pointer differences : http://www.geeksforgeeks.org/g-fact-5/
In your example both prt1 as well as ptr2 are pointing to same char. And you can get same effects for ptr1/ptr2 using cout what you get for arr1.
So, below all will print same thing:-
cout << arr1;
cout << ptr1;
cout << ptr2;
If you want to create new array using ptr2 with same contents as of arr1, then
ptr2 = malloc(strlen(ptr1) + 1);
strcpy(ptr2, ptr1);
May this would help
link: http://ideone.com/Nwqd22
#include <iostream>
using namespace std;
char* fun(){
char * returnValue = "String";
return returnValue;
}
int main() {
char * firstVariable;
firstVariable = fun();
cout << firstVariable;
return 0;
}