Segmentation fault while passing string array [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
I went through similar question on stackoverflow but it did not solve my issue
I am trying to send string array as below
void manipulateString( char *);
int hashTable (int &, char * );
const int HTsize = 10;
int main()
{
const int size = 100;
char inputString[size];
cout << " Enter first names ( separate by a space ) \n ";
cin.getline(inputString,size);
manipulateString(inputString);
return 0;
}
void manipulateString (char *input)
{
int firstNamelen;
int hIndex=0,newIndex=0;
int totalName = 0;
char *firstname;
firstname = strtok(input, " "); // separate firstname
while (firstname != NULL)
{
firstNamelen = strlen(firstname);
hIndex = hashfunction(firstname,firstNamelen);
newIndex=hashTable(hIndex, firstname);
cout << "\n\n ( " << firstname << " ) is stored at index [" << hIndex << "] of hash table " << endl;
firstname = strtok(NULL, " " ); // next first name
}
}
When it reaches to void manipulateString (char *input) it gives segmentation fault. what is the issue?

Given that hashfunction and hashTable are not leading to a segmentation fault...
You can only read size-1 characters.
Check cin.fail() to see whether cin.getline was successfull. If not the string might not be NULL terminated. If the string is not NULL terminated, strlen or strtok might lead to a segmentation fault.

Related

const char* pointer handling (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 months ago.
Improve this question
Hi everyone I have a simple task in C++:
-> writing a program that takes a string from user input and loops over the characters in the string via a pointer.
If I understand correctly, then a previously declared string name; variable can also be accessed via const char*, implying that I can declare a pointer in the following manner: const char *pName = &(name[0]);. When printing the pointer, however, not the memory address but the actual variable is displayed in the terminal (see my code below). This prevents me from incrementing the pointer (see for loop).
Filename: countchar.cpp
#include <iostream>
using namespace std;
int main() {
string name;
std::cout << "Provide a string." << endl;
std::cin >> name;
const char *pName = &(name[0]);
cout << pName << endl;
// further downstram implementation
// int len = name.length();
// for(int ii = 0; ii < len; ii++){
// std::cout << "iteration" << ii << "address" << pName << endl;
// std::cout << "Character:" << *pName << endl;
// (pName+1);
// }
return 0;
}
Terminal output:
$ g++ countchar.cpp -o count
$ ./count
$ Provide a string.
$ Test
$ Test
As I am a quite a noob in regard to C++ help and an explanation are both highly appreciated (No material found online that solves my problem). Thanks in advance!
The operator << overloaded for a pointer of the type char * such a way that it outputs the string pointed to by the pointer.
So according to the assignment instead of these statements
const char *pName = &(name[0]);
cout << pName << endl;
you need to use a loop like
for ( const char *pName = &name[0]; *pName != '\0'; ++pName )
{
std::cout << *pName;
}
std::cout << '\n';

warning C4552: '>>': result of expression not used [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
#include <iostream>
int main() {
int manic;
std::cout << "Enter Size of Array" << "/n";
std::cin >> size; // << "/n";
size = manic;
static const int arr[size];
for(int i = 0; i < size; i++) {
std::cout << "Enter" << i << "Element" << "/n";
std::cin >> (arr[i]); // Error Is Shown in this Line
}
bool r = is_even(arr, size);
std::cout << r;
return 0;
}
My first post here .I typed this code in Visual Studio 2019.The Microsfot Documents do not help.
The compiler gives you the hint that you may uninentionally override a value
std::cin >> size;// << "/n";
size = manic;
You let the user input a value and then override it with another, by the way uninitialized, value.

Corrupted array [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 5 years ago.
Improve this question
char arr[10]="\0",arr1[2][5]={'\0'};
cout<<"enter the full line : ";
gets(arr);
for (int i=0;i<1;i++)
{
for (int j=0;j<10;j++)
{
if(j<=4)
{
arr1[0][j]=arr[j] ;
}
else if (j>4)
{
arr1[1][j-5]=arr[j] ;
}
}
}
for(int j=0;j<5;j++)
{
cout<<arr1[0][j]<<" ";
}
cout<<endl;
for(int j=0;j<5;j++)
{
cout<<arr1[1][j]<<" ";
}
Here what i am trying to do is converting a 1d array in to 2d array.
my main purpose is to store 1d array on a 2d and when the first row is completed it should shift the string to next row it is doing all the as i have declared the arr[10] and inputting 10 charcter string through get(arr) it is storing the array as i want but at the end displays an error window i dont know why the program is running perfect as well as giving this error window
my input : hanzlaamja (10charcters)
my output:
h a n z l
a a m j a
according to my wish but the main problem is the error window.
note : there is nothing in error box or warning box.
My program is working perfectly, but i am getting an error of array corruption.
Can anybody help me out? I would be very thankful
please see this error message
full picture
The problem is that you read in 10 characters (e.g. "hanzlaamja") and the string termination character '\0', which is automatically added by gets. Thereby you exceed array bounds, as this would require space for 11 characters. So it would already work if you wrote char arr[11];. But as mentioned in the comments, do not use gets; it is unsafe and it does not prevent you from exceeding array bounds. The following snippet shows how to do this part better:
...
char arr[11]="\0",arr1[2][5]={'\0'};
cout<<"enter the full line : ";
// gets(arr);
if (!fgets(arr,11,stdin)) {
cout << "no value read." << endl;
return 1;
}
...
A lot of your loops could be written shorter / better readable. But that's not the actual topic.
Adding to the great point pointed out by #Stephan Lechner, I have composed a solution "as close as possible" to your original.
Compiled under visual studio 2017.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
cout << "main - start" << endl;
const size_t numOfRows = 2;
const size_t numOfCol = 5;
const size_t numCharsInSingleDimArray = 10;
char arr[numCharsInSingleDimArray] = { '\0' }, arr1[numOfRows][numOfCol] = { '\0' };
cout << "enter the full line : ";
gets_s(arr); // Note:If the buffer (arr) is too small to contain the input line and null terminator, these functions invoke an invalid parameter handle.
cout << "main - entered:" << arr << endl;
char* twoDimArrStartLoc = &(arr1[0][0]); // as user4581301 pointed out, it is also possible to "approach" it by treating the two dimensional array as a contiguous bytes in memory
for (size_t i = 0, j = 0; i< numCharsInSingleDimArray; ++i, ++j)
{
twoDimArrStartLoc[j] = arr[i];
}
cout << "main - after converting the 1d array into 2d array, arr1 is:" << endl;
for (size_t i = 0; i < numOfRows; ++i)
{
for (size_t j = 0; j < numOfCol; ++j)
{
cout << "arr1[" << i << "]" << "[" << j << "]:" << arr1[i][j] << " ";
}
cout << endl;
}
// for debug - you can remove this if not needed...
cout << "main - end, enter any key and press enter to terminate..." << endl;
char tmp;
cin >> tmp;
return 0;
}
Hope it helps.
Cheers,
Guy.
thank you everyone for your support the MAIN mistake i was doing is the use of gets(arr) and doing arr[10] as if you are using function gets(arr) you have to give one extra index which is used by this function gets(arr) i.e. arr[11]
solved :)

How does this function work? char* getname(); 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 5 years ago.
Improve this question
I'm starting out on how to code in c++.
I've been reading c++ primer plus (5th edition) book and came across an example program which I don't fully understand. Basically, the program asks for your last name and gives you the address of where it gets stored:
#include <iostream>
#include <cstring>
using namespace std;
char* getname();
int main();
{
char* name;
name = getname();
cout << name << " at " << (int*)name << endl;
delete [] name;
name = getname();
cout << name << " at " << (int*)name << endl;
delete [] name;
return 0;
}
char* getname()
{
char temp[80];
cout << "Enter last name: ";
cin >> temp;
char* pn = new char [strlen(temp)+1];
strcpy(pn, temp);
return pn;
}
I don't quite get why char* getname() function needs the dereference operator. I'm having a little bit of trouble understanding this program overall, hehe.
Sorry if this comes across like a silly question, but I'm quite stuck. That's all. Thank you!..
name - it's a pointer to first char in sequence.
std::cout with << - has different behavior depending on what you give him.
If its pointer to first char in sequence (char* name) - cout printing this sequence.
If its pointer to int number - cout printing address of this number in memory (0x1105010)
(int*) - casting to pointer to int.

C++ char to string acting funky [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 6 years ago.
Improve this question
This is the code:
int main(){
string word= "word";
char ciphered[word.length()];
for(int i=0; i<word.length(); i++)
{
int current_position = (int) word[i];
int new_position = current_position + 2;
char this_char = (char) new_position;
ciphered[i] = this_char;
}
string str(ciphered);
cout << str << endl ;
}
When i run this it prints this:
But when i do this:
for(int i = 0; i<sizeof(ciphered); i++)
{
cout << ciphered[i] << endl ;
}
it prints out the same thing but without last three signs and that is correct
but whenever i try to convert this char array to string it adds these last three weird signs and i dont know why
First of all, this:
char ciphered[word.length()];
is not legal C++ code, though gcc may accept it. But second that you do not need really that char array, as you can access individual symbols with std::string itself:
string word= "word";
string ciphered( word.length(), ' ' );
for(int i=0; i<word.length(); i++)
{
ciphered[i] = word[i] + 2;
}
cout << ciphered << endl;
your code prints additional symbols because you did not put null terminator on C-style string and sent it through std::ostream which leads to UB and prints garbage that happens in memory after your char array until it suddenly finds null terminator or crash because of access of invalid memory.