getting segmentation fault string s=s+"A"; - c++

CASE 1
If i use
string s=s+"A" i get segmentation fault
#include <iostream>
#include <string>
using namespace std;
int main() {
string s=s+"A";
return 0;
}
CASE 2
but if i use
string s;
s=s+"A" it works fine
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
s=s+"A";
return 0;
}
what is the reason of segmentation fault in case 1.
Also had it been any other datatype like int it works fine.

string s hasn't been initialized here yet:
string s=s+"A";
This is why you are getting a segmentation fault.
In the second case:
string s; // default value ""
s = s+ "A"; // you are getting "" + "A"

Related

I'am working on a C++ program where I'am facing a error while execution of if-else statement [duplicate]

#include <iostream>
using namespace std;
int main() {
char word[10]="php";
char word1[10]="php";
if(word==word1){
cout<<"word = word1"<<endl;
}
return 0;
}
I don't know how to compare two char strings to check they are equal. My current code is not working.
Use strcmp.
#include <cstring>
// ...
if(std::strcmp(word, wordl) == 0) {
// ...
}
Use std::string objects instead:
#include <iostream>
#include <string>
using namespace std;
int main() {
string word="php";
string word1="php";
if(word==word1){
cout<<"word = word1"<<endl;
}
return 0;
}
To justify c++ tag you'd probably want to declare word and word1 as std::string. To compare them as is you need
if(!strcmp(word,word1)) {
word and word1 in your submitted code are pointers. So when you code:
word==word1
you are comparing two memory addresses (which isn't what you want), not the c-strings they point to.
#include <iostream>
**#include <string>** //You need this lib too
using namespace std;
int main()
{
char word[10]="php";
char word1[10]="php";
**if(strcmp(word,word1)==0)** *//if you want to validate if they are the same string*
cout<<"word = word1"<<endl;
*//or*
**if(strcmp(word,word1)!=0)** *//if you want to validate if they're different*
cout<<"word != word1"<<endl;
return 0;``
}

how can I use string variable in system("say string variable")?

/* I thought of doing in this way, but it invalid.
so any help will be appreciated. */
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name = "Karma";
string greet = "How was your day?";
string sums = name + greet;
system("say %s", sums) // not working
// system("say sums") not working
return 0;
}
You can use:
system(("say" + sums).c_str())
Instead of:
system("say %s", sums)

Segmentation fault in reversing string program

I am trying to reverse a string. Can someone explain me why this is giving me segmentation fault?
#include <iostream>
#include <string>
using namespace std;
int main(){
string str,rstr;
int len=str.length(),i=0;
cin>>str;
while(str[i]!='\0'){
rstr[--len]=str[i++];
}
rstr[str.length()]='\0';
cout<<rstr;
return 0;
}
P.S.: Need to reverse it without using library functions.
If you want to go the way you are doing it, for practice purposes, try this changes and start from there
#include <iostream>
#include <string>
using namespace std;
int main(){
string str,rstr;
cin>>str; // --- Moved this line up
rstr = str; // --- Added this line
int len=str.length(),i=0;
while(str[i]!='\0'){
rstr[--len]=str[i++];
}
rstr[str.length()]='\0';
cout<<rstr;
return 0;
}
Or just use reverse iterator
std::string s = "Hello";
std::string r(s.rbegin(), s.rend());
str is nothing but a declared string here:
int len=str.length(),i=0;
So you can't do str.length()
Do something like:
#include <iostream>
#include <string>
using namespace std;
int main(){
string str,rstr;
int len,i=0;
cin>>str;
len = str.length();
while(str[i]!='\0'){
rstr[i++]=str[--len];
}
rstr[str.length()]='\0';
cout<<rstr;
return 0;
}

Segmentation Fault while Reading from File

I am trying to print last 10 lines of a file. Following is my code, but it is giving a segmentation fault due to fscanf. While running with gdb the fault reads : vfscanf.c: No such file or directory.
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
int main()
{
FILE *fp = fopen("microfile.txt","r");
char *c[10];
int idx = 0;
cout<<fp<<"\n";
while(!feof(fp))
{
if(idx<10)
{
fscanf(fp,"%s",c[idx]);
idx++;
}
else if(idx==10)
{
for(int i=0;i<idx-1;i++)
{
c[i] = c[i+1];
}
fscanf(fp,"%s",c[idx-1]);
}
}
int i=0;
while(i<10)
{
cout<<c[i]<<"\n";
i++;
}
}
The source of the problem comes from the fact you have an array of pointers on this line:
char* c[10];
And later on in the program you attempt to assign character values to these pointers. Maybe you meant for just an array of characters instead:
char c[10];
Moreover, use of the Standard library is recommended. Try using std::string and standard streams and your program can be made more maintainable:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string s;
s.assign(
std::istreambuf_iterator<char>(std::ifsteam("microfile.txt").rdbuf()),
std::istreambuf_iterator<char>());
for (char c : s)
std::cout << c << std::endl;
}

How to correct a segmentation fault?

I keep getting an error Segmentation fault (core dumped), so I ran valgrind. It is my first time using it, so not sure what to do to get my code working. I've tried changing it, but it still says core dumped, or I receive more errors than I had before. I did try debugging the code with gdb, but the debugger was not working properly.
and corresponding product.h
#ifndef GS_PRODUCT
#define GS_PRODUCT
#include <iostream>
#include <string>
using namespace std;
class Product
{
private:
int plu_code;
string name;
double price;
bool by_weight;
double inventory;
public:
Product(int p_code = 0, string p_name = "", bool p_by_weight = true, double p_price = 0.0, double p_inv = 0.0);
bool sold_by_weight(void);
double compute_cost(double weight_or_unit);
string get_name(void);
int get_plu_code(void);
double get_price(void);
double get_inventory(void);
};
#endif
This is my product.cpp:41
#include <iostream>
#include <string>
#include "product.h"
using namespace std;
Product::Product(int p_code, string p_name, bool p_by_weight, double p_price, double p_inv)
{
plu_code = p_code;
name = p_name;
by_weight = p_by_weight;
price = p_price;
inventory = p_inv;
}
bool Product::sold_by_weight(void)
{
return by_weight;
}
double Product::compute_cost(double weight_or_units)
{
inventory -= weight_or_units;
return weight_or_units * price;
}
string Product::get_name(void) {
return name;
}
int Product::get_plu_code(void) {
return plu_code;
}
double Product::get_price(void) {
return price;
}
double Product::get_inventory(void) {
return inventory;
}
This is my main program store
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <sstream>
#include "product.h"
#include "Tokenizer.h"
#include "LookupTable.h"
using namespace std;
LookupTable<Product *> table;
int numProducts = 0;
void checkout()
{
}
int main()
{
int plu;
string name;
int weight;
double inv;
double price;
table.addRange(0, 9999);
table.addRange(90000, 99999);
// std::string line;
//Input file
ifstream infile("inventory.csv");
if(infile.fail())
perror("Could not open file ");
stringstream ss;
while(infile.good())
{
string line = "";
//read a product info from file
getline(infile, line);
Tokenizer tok(line, ",");
ss<<line;
//string token = tok.next();
ss >> plu >> name >> weight >> price >>inv;
table[plu] = new Product(plu, name,weight, price,inv);
numProducts++;
}
infile.close();
checkout();
ofstream outfile;
outfile.open("output.csv");
for(int i=0; i< numProducts; i++)
{
outfile<< table[i]-> get_plu_code() << "" << table[i]->get_name()<<""<<table[i]->sold_by_weight() <<""<<table[i]->get_price() <<""<<table[i]->get_inventory();
}
outfile.close();
return 0;
}
The meaning of a segmentation fault is that you tried to access a page which doesn't have the permissions (normally read/write permission but possibly also executable permission) needed for the operation. That is, the system tells you that you tried to access something which isn't really there or which is inaccessible.
There are many typical problems eventually resulting in segmentation faults. Here are a few of those:
An uninitialized pointer is dereferenced.
A null pointer is dereferenced.
An array is accessed outside its boundaries, thus accessing random memory as if it were an array element.
A released object is being used as if it is live, e.g., an object after being deleted or an object which was on the stack.
... and many more similar stuff.
To get help with the actual segmentation fault you have, you'll need to provide a short but complete example exhibiting the problem. Quoting a few lines which you think are related to the problem are generally rather unlikely to actually contain the actual problem.
You don't appear to have any value inventory to return from Product::get_inventory(). I would think that either this wouldn't compile, or you have some code that you haven't shown that is relevant. Most likely, the latter is the case, and the variable inventory is not yet initialized at the time that it is returned.