Program executes correctly then segfaults - c++

At the end of the program, my array prints out properly, and then the program segfaults. Why?
#include <iostream>
#include <stdio.h>
#include <iomanip>
#include <string.h>
using namespace std;
int main(int argc, char *argv[]) {
FILE *file = fopen(argv[1], "r");
struct item{
char type[9];
int price;
bool wanted;
};
item items[20]; char temp[8];
for (char i = 0; i < 100; i++)
{
if (fscanf(file,
"%[^,], %[^,], %d",
items[i].type,
temp,
&items[i].price) != 3)
break;
else if (!strcmp(temp, "for sale"))
items[i].wanted = false;
else if (!strcmp(temp, "wanted"))
items[i].wanted = true;
else
cout << "aaaagghghghghhhh!!!" << endl;
}
for (char i = 0; i < 100; i++)
{
cout << items[i].type << endl;
cout << items[i].price << endl;
cout << items[i].wanted << endl;
}
}

Your array is declared with only 20 spaces, yet your loop goes to 100. Maybe change your array to have 100 spaces.
Use
item items[100];
Overflowing arrays leads to undefined behavior. It is possible that your code wrote into memory required by the C++ run-time during program stack unwinding, etc.

Related

C++ - Checking if a word is palindrome in struct data type

I want to know how to check if a word is palindrome in struct data type or object whatever you want to call it. I want to read a data from file then I need to check if that type of word that I have read is a palindrome or not. Also i need to reverse order of the words but I did that so do not need any help about that.
Here is the code:
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
struct lettersStr
{
string name;
string object;
};
int main(int argc, char** argv)
{
ifstream letter;
letter.open("letter.txt");
lettersStr things[200];
int numberOfThings= 0;
while(letter >> letter[numberOfThings].name >> letter[numberOfThings].object)
{
numberOfThings++;
}
for (int i = 0; i < numberOfThings; i++)
{
cout << letter[i].name << " " << letter[i].object<< endl;
}
string names;
for (int i = 0; i < numberOfThings; i++)
{
names= things[i].name;
}
for (int i = numberOfThings- 1; i >= 0; i--)
{
cout << things[i].name << endl;
}
bool x = true;
int j = names.length() - 1;
for (int i = 0; i < j; i++,j--)
{
if (things[i].name.at(i) != things[i].name.at(j))
x = false;
if (x)
{
cout << "String is a palindrome ";
}
else
cout << "String is not a palindrome";
}
And here is the cout:
Kayak Audi
Ahmed Golf7
Ahmed
Kayak
String is not a palindrome
String is not a palindrome
I think major problem is this:
for (int i = 0; i < j; i++,j--)
{
if (things[i].name.at(i) != things[i].name.at(j))
x = false;
As you can see it wont cout right way of checking if a word is palindrome or not.
P.S: If this is a stupid question I am sorry, I am a beginner in C++ programming.
Cheers
As already pointed out in the comments, for (int i = 0; i < j; i++,j--) loops though things and the letters of their names simultaneously. You also have to account for cases where you compare a lower and an upper case letter such as the 'K' and 'k' at the beginning and end of 'Kayak'. You can use std::tolower for this.
Here is an example (live demo):
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
bool is_palindrome(std::string name)
{
if (name.empty())
return false;
// As has been pointed out, you can also use std::equal.
// However, this is closer to your original approach.
for (unsigned int i = 0, j = name.length()-1; i < j; i++,j--)
{
if (std::tolower(name.at(i)) != std::tolower(name.at(j)))
return false;
}
return true;
}
struct lettersStr
{
string name;
string object;
};
int main(int argc, char** argv)
{
std::vector<lettersStr> vec = {lettersStr{"Kayak","Boat"},lettersStr{"Audi","Car"}};
for (const auto &obj : vec)
if (is_palindrome(obj.name))
std::cout << obj.name << " is a palindrome" << std::endl;
else
std::cout << obj.name << " isn't a palindrome" << std::endl;
}
It gives the output:
Kayak is a palindrome
Audi isn't a palindrome

Lowercasing Capital Letters in char array[] in C++ through Pointers

I am trying to use pointers to recursively lowercase all capital letters
using the C++ programming language. Below is the code snippet:
// Example program
#include <iostream>
#include <string>
using namespace std;
void all_lower(char* input) {
if ( *input ) {
cout << input << endl;
return;
}
if ( *input >= 'A' && *input <= 'Z') {
*input += 32; // convert capital letter to lowercase
}
cout << *input << endl;
all_lower(++input); // simply move to next char in array
}
int main() {
char test[] = "Test";
all_lower(test);
return 0;
}
The output ends up being:
"Test"
even though I tried to increase the ASCII code value of the element by 32.
You are exiting the function on the first non-null character detected, which is 'T', and then you output the entire array before exiting, so you are seeing the original unmodified input. You are not recursing through the array at all. You need to recurse through the array until you reach the null terminator.
You need to change this:
if ( *input ) {
cout << input << endl;
return;
}
To this instead:
if ( *input == 0 ) {
return;
}
Then the function will work as expected.
That being said, I suggest you remove the cout statements from the function, and do a single cout in main() after the function has exited. This will speed up the function, and prove that the content of the test[] array is actually being modified:
#include <iostream>
using namespace std;
void all_lower(char* input)
{
if ( *input == 0 ) {
return;
}
if ( *input >= 'A' && *input <= 'Z') {
*input += 32; // convert capital letter to lowercase
}
all_lower(++input); // simply move to next char in array
}
int main()
{
char test[] = "TEST";
cout << "Before: " << test << endl;
all_lower(test);
cout << "After: " << test << endl;
return 0;
}
Live Demo
And, since you are using C++, consider removing all_lower() altogether and use the STL std::transform() algorithm instead:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
char test[] = "TEST";
cout << "Before: " << test << endl;
transform(test, test+4, test, [](char ch){ return tolower(ch); });
cout << "After: " << test << endl;
return 0;
}
Live Demo
Something short and easy:
#include <iostream>
#include <string>
using namespace std;
void all_lower(const char* input) {
if (!*input) {
std::cout << std::endl;
return;
}
std::cout << (char)(std::isalpha(*input) ? tolower(*input) : *input);
all_lower(++input); // simply move to next char in array
}
int main() {
all_lower("Test");
return 0;
}

Heap Corruption at class destructor?

I've been trying to figure this out for hours now, and I'm at my wit's end. I would surely appreciate it if someone could tell me when I'm doing wrong.
I wrote a c++ code with class implementing a simple stack, trying to push and pop random stream of characters. It seems to work fine, but at the end of the file, it produces some sort of runtime error:
HEAP CORRUPTION DETECTED: after Normal block....
Since the error occurs at the end of the file, my guess is that there is a problem at deleting the pointer(class destructor). However, I have no idea what is wrong with the destructor I wrote.
Also, after some trial and error, I found out that if I address a bigger number to unsigned integer value iter1 (ex: 80), the runtime error does not occur. Could you explain what is the problem here, and how to bypass it?
stack.h:
class sstack
{
public:
sstack(int length = 256);
~sstack(void);
int sstackPop(char &c);
int sstackPush(char c);
bool isempty();
bool isFull();
protected:
private:
char *sstackBuffer;
int sstackSize;
int sstackIndex; // Initial = -1
};
stack.cpp:
#include "stack.h"
#include <iostream>
using namespace std;
sstack::sstack(int length)
{
sstackIndex = -1;
if (length > 0)
sstackSize = length;
else
sstackSize = 256;
sstackBuffer = new char[sstackSize];
}
sstack::~sstack(void)
{
delete[] sstackBuffer;
}
bool sstack::isempty()
{
if (sstackIndex < 0)
{
cout << "is empty!(isempty)" << endl;
return 1;
}
else
return 0;
}
bool sstack::isFull()
{
if (sstackIndex >= sstackSize)
return 1;
else
return 0;
}
int sstack::sstackPop(char &c)
{
if (!isempty())
{
c = sstackBuffer[sstackIndex--];
cout << sstackIndex << endl;
return 1;
}
else
{
cout << "is empty!(sstackPop)" << endl;
return 0;
}
}
int sstack::sstackPush(char c)
{
if (!isFull())
{
sstackBuffer[++sstackIndex] = c;
return 1;
}
else{
return 0;
}
}
main.cpp:
#include <iostream>
#include "stack.h"
#include <string>
using namespace std;
int main(){
unsigned int iter1 = 5;
unsigned int iter2 = 800;
sstack stackDefault;
sstack stack1(iter1);
sstack stack2(iter2);
char buffer[80];
memset(buffer, 0x00, 80);
char BUFFER[80] = "A random stream of characters";
strcpy_s(buffer, 80, BUFFER);
for (int i = 0; i< strlen(buffer); i++)
{
cout << " stack1: " << stack1.sstackPush(buffer[i]);
cout << " stack2: " << stack2.sstackPush(buffer[i]);
cout << " stackD: " << stackDefault.sstackPush(buffer[i]);
cout << " i : "<< i << endl;
}
cout << "out of Pushes" << endl;
int i = 0;
memset(buffer, 0x00, 80);
while (!stack1.isempty())
stack1.sstackPop(buffer[i++]);
cout << buffer << endl;
getchar();
}
sstackBuffer[++sstackIndex] = c;
Will write past the end of sstackBuffer when the stack only has one element left.
If you consider a stack of size 1. In the first call to push that line would evaluate to:
sstackBuffer[1] = c;
Which is beyond the memory you've allocated.
Be sure you're aware of the difference between pre-increment and post-increment operators. By your code example I would suggest you use post-increment in push and pre-increment in pop.

Why do I get an Segmentation fault error

My code works fine on codeblocks compiler on my computer but when I upload it to an online editor I get an Segmentation fault error and I don't know why.
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <fstream>
using namespace std;
int main(int argc, char *argv[]) {
ifstream stream(argv[1]);
char line[1000];
int x,last=-1;
while (stream>>line)
{
x = atoi(strtok(line,","));
cout<<x;
last=x;
while(x=atoi(strtok(NULL,",")))
{
if(x!=last)
{
cout<<","<<x;
last=x;
}
}
cout<<endl;
}
return 0;
}
You are given a sorted list of numbers with duplicates. Print out the sorted list with duplicates removed.
And this is the input
6,7,8,9,9,10,11,12,13,14,15
11,12,13,14,15,16,17,18,19,20
2,2,2,2,2
10,11,12,13,14,15,16,16,17
13,14,14,15,16,17,17,17,18
15,16,17,17,18,18,18,18,19,19,20
2,3,4,5,5
13,14,15,16,17
10,11,12,13,14,15,15,15,15,16,16,16
12,13,14,15,16,17,17,18
5,6,7,8,9,10,11
14,14,14,15,15,16,17,17,18,19,19,20,21,22
13,14,15,16,16,17,17,18
15,16,17,18,19,20,21,21,21,21,22,22
6,6,6,7,8,9,10,11,11,11,12,12,13
12,12,13,14,15,15,16,17,17,18,19,19,20,21
8,9,9,9,10,10,11,12,13,13,14,15
12,13,14,15,16,17,18
1,1,1,2,2,3,3,4,4
1,2,3,4
Since you're asking us to guess, let's start at the top ....
The code doesn't check that argv[1] is valid. If not, then you just dereferenced a null-pointer, and that caused your segmentation fault.
Does your "online editor" pass parameters? I suggest checking argc > 1.
Next, your code looks like it will pass a null pointer to atoi at the end of every line. That's another segmentation fault.
You are calling atoi with the result of strtok.
If strtok doesn't find anything it returns a null pointer.
This is the case at the end of the line.
So you are passing a null pointer to atoi which then leads to a crash.
Using your example this should work:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <fstream>
using namespace std;
int main(int argc, char *argv[])
{
ifstream stream(argv[1]);
char line[1000];
char* ln;
char* num;
int x;
int last;
while (stream >> line)
{
ln = line;
last = -1;
while (num = strtok(ln, ","))
{
x = atoi(num);
if (x != last)
{
if(last != -1) cout << "," << x;
else cout << x;
last = x;
}
ln = NULL;
}
cout << endl;
}
return 0;
}
EDIT: Another solution with checking for valid paramters and w/o strtok and atoi:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <fstream>
using namespace std;
int main(int argc, char *argv[])
{
if (argc < 2) {
cout << "Usage: " << argv[0] << " <file>";
return 1;
}
ifstream stream(argv[1]);
if (!stream.is_open())
{
cout << "Failed to open file \"" << argv[1] << "\"";
return 2;
}
char line[1000];
while (stream >> line)
{
int last = -1;
int x = 0;
for (char* pos = line; pos < line + strlen(line); pos++)
{
if (*pos >= '0' && *pos <= '9')
{
x = (x * 10) + (*pos - '0');
}
else
{
if (last != x)
{
if (last != -1) {
cout << ',';
}
cout << x;
last = x;
}
x = 0;
}
}
cout << endl;
}
return 0;
}

Access violating writing location (visual studio 2008) Code based on pointers

The main problem is after sem->i = a; is used when yylex is called and c isalpha
sem->s[i] = c; doesn't work because sem->s[i] has an issue with the adress it points to.
more details:
So what i want to do is to open a txt and read what it is inside until the end of file.
If it's an alfanumeric (example: hello ,example2 hello45a) at the function yylex i put each of the characters into an array(sem->s[i]) until i find end of file or something not alfanumeric.
If it's a digit (example: 5234254 example2: 5) at the function yylex i put each of the characters into the array arithmoi[]. and after with attoi i put the number into the sem->i.
If i delete the else if(isdigit(c)) part at yylex it works(if every word in the txt doesn't start with a digit) .
Anyway the thing is that it works great when it finds only words that starts with characters. Then if it finds number(it uses the elseif(isdigit(c) part) it still works...until it finds a words starting with a character. when that happens there is an access violating writing location and the problem seems to be where i have an arrow. if you can help me i would be really thankfull.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <iostream>
using namespace std;
union SEMANTIC_INFO
{
int i;
char *s;
};
int yylex(FILE *fpointer, SEMANTIC_INFO *sem)
{
char c;
int i=0;
int j=0;
c = fgetc (fpointer);
while(c != EOF)
{
if(isalpha(c))
{
do
{
sem->s[i] = c;//the problem is here... <-------------------
c = fgetc(fpointer);
i++;
}while(isalnum(c));
return 1;
}
else if(isdigit(c))
{
char arithmoi[20];
do
{
arithmoi[j] = c;
j++;
c = fgetc(fpointer);
}while(isdigit(c));
sem->i = atoi(arithmoi); //when this is used the sem->s[i] in if(isalpha) doesn't work
return 2;
}
}
cout << "end of file" << endl;
return 0;
}
int main()
{
int i,k;
char c[20];
int counter1 = 0;
int counter2 = 0;
for(i=0; i < 20; i++)
{
c[i] = ' ';
}
SEMANTIC_INFO sematic;
SEMANTIC_INFO *sema = &sematic;
sematic.s = c;
FILE *pFile;
pFile = fopen ("piri.txt", "r");
do
{
k = yylex( pFile, sema);
if(k == 1)
{
counter1++;
cout << "it's type is alfanumeric and it's: ";
for(i=0; i<20; i++)
{
cout << sematic.s[i] << " " ;
}
cout <<endl;
for(i=0; i < 20; i++)
{
c[i] = ' ';
}
}
else if(k==2)
{
counter2++;
cout << "it's type is digit and it's: "<< sematic.i << endl;
}
}while(k != 0);
cout<<"the alfanumeric are : " << counter1 << endl;
cout<<"the digits are: " << counter2 << endl;
fclose (pFile);
system("pause");
return 0;
}
This line in main is creating an uninitialized SEMANTIC_INFO
SEMANTIC_INFO sematic;
The value of integer sematic.i is unknown.
The value of pointer sematic.s is unknown.
You then try to write to sematic.s[0]. You're hoping that sematic.s points to writable memory, large enough to hold the contents of that file, but you haven't made it point to anything.