Error reading character of string C++ - c++

I showed my codes and i have an error reading character of string. Everything is okey in my debugger until the NULL.
*Warning C4715 `String::equas`: not all control paths return a value*
I can not use it because I am using a NULL pointer for the parameter.
How can I solve this problem?
Thanks a lot and have a nice day!
Header:
class String
{
public:
String();
bool empty();
String(char * other_str);
bool equals(const String other_str);
private:
char* m_str;
};
My Codes:
#include "String.hpp"
#include <string>
#include<iostream>
int my_len(const char* p) {
int c = 0;
while (*p != '\0')
{
c++;
*p++;
}
return c;
}
String::String()
:m_str(NULL)
{
}
String::String(char * other_str)
{
}
bool String::empty()
{
return true;
}
bool String::equals(const String other_str)
{
if (m_str == NULL && other_str.m_str == NULL) {
return true;
}
if (m_str == NULL && other_str.m_str != NULL) {
return false;
}
if (m_str != NULL && other_str.m_str == NULL) {
return false;
}
if (m_str != NULL && other_str.m_str != NULL) {
int mystrlen = my_len(m_str);
int myrhslen = my_len(other_str.m_str);
if (mystrlen != myrhslen)
{
return false;
}
else
{
for (int i = 0; i < mystrlen; i++)
{
if (m_str[i] != other_str.m_str[i])
{
return false;
}
else {
return true;
}
}
}
}
}
i will add this codes:
int mylen(const char* p) {
int c = 0;
while (*p != '\0')
{
c++;
*p++;
}
return c;
}
void my_cpy(char dest, const char* src) {
int i = 0;
while (src[i] != '\0') {
dest[i] = src[i];
i++;
}
dest[i] = '\0';
}
char mytrdup(const char *s) {
char* d = (char*)malloc((my_len(s) + 1) * sizeof(char));
if (d == NULL) {
return NULL;
}
else{
my_cpy(d, s);
}
return d;
}

String empty_string2(NULL);
This will invokde the constructor version :
String::String(char* other_str) {}
which does nothing, leaving the m_str pointer dangling/uninitialized. You should change this constructor somehow, either by copying the string and setting the m_str pointer accordingly, or by setting m_str to the same address as the parameter. Either case it depends on what you want to achieve.
Besides, many other problems exist in your code. I notice already this one in you implemented function my_len. you should change *p++ into p++. I wonder how this passed the compilation btw, since the parameter is a const char*.
Finally, the compiler's warning is correct and very clear, although it is not the source of the problem you are facing for the time being.
EDIT: to make a duplicate copy of the string, you can write you constructor like this:
String::String(const char* other_str)
{ m_str = (other_str ? strdup(other_str) : other_str); }
And besides, preferably use null_ptr instead of NULL in your code. Since C++11, this is the standard for null pointers.

I add TEST_TRUE and then that work correctly.

Related

Array Wrapper Corrupts Heap

Sequel to: array wrapper corrupts stack
The project:
I am working on a std::vector replacement.
The error:
I get a heap corruption error whenever I attempt to delete a temporary array I am creating in order to store the copied elements of another array that I delete in order to reallocate it when my array gets resized. (It seems that if I try to assign one array to another, I actually end up assigning the pointer to the array to the other array instead of copying the elements. Truly crazy stuff).
I read online that this error may actually come from the part where I actually interact with the array, but the error only pops out when I attempt to delete it.
Where I interact with the array is the function _tempcpy. I pass a pointer to a source and destination array and copy each element from the source to the destination. I struggled a bit with making sure that the array would start from 0 and not 1 and in the process I messed a bit too much with the element_count member, so it may be that i am somehow writing outside of bounds and I have stared so much at the code I can't see the issue.
The code:
template<class T> class dyn_arr
{
public:
dyn_arr(void)
{
this->array = {};
this->element_count = {};
}
~dyn_arr(void)
{
this->dealloc();
}
bool alloc(unsigned int element_count)
{
if (0 == element_count)
{
element_count = 1;
}
if (this->array != nullptr)
{
T* temp = new T[this->element_count];
if (false == this->_tempcpy(&this->array, &temp, this->element_count))
{
return false;
}
delete[] this->array;
this->array = new T[this->element_count];
if (false == this->_tempcpy(&temp, &this->array, this->element_count))
{
return false;
}
delete[] temp;
if (nullptr != this->array)
{
return true;
}
}
else
{
this->array = new T[this->element_count];
if (nullptr != this->array)
{
return true;
}
}
return false;
}
bool dealloc(void)
{
if (nullptr == this->array)
{
return false;
}
delete[] this->array;
return true;
}
bool add(T Object)
{
if (0 == Object)
{
return false;
}
if (true == this->alloc(this->element_count))
{
this->array[this->element_count] = Object;
++this->element_count;
return true;
}
return false;
}
T get(unsigned int index)
{
if (index > this->element_count)
{
return T{};
}
return this->array[index];
}
unsigned int get_count(void)
{
return this->element_count;
}
private:
bool _tempcpy(T** src, T** dest, unsigned int count)
{
if ((nullptr == src) || (nullptr == dest) || (0 == count))
{
return false;
}
for (unsigned int i = 0; i < count; ++i)
{
*dest[i] = *src[i];
}
return true;
}
T* array;
unsigned int element_count;
};
int main()
{
dyn_arr<int> pNr = {};
pNr.add(1);
pNr.add(2);
pNr.add(3);
for (int i = 0; i < pNr.get_count(); ++i)
{
printf("%d\n", pNr.get(i));
}
getchar();
return 0;
}
In your alloc function there lie a few problems, such as:
if (0 == element_count)
{
element_count = 1;
}
is unnecessary. Instead, you can just do a +1 where necessary which is almost everywhere except the temp dynamic array.
bool alloc(...)
{
this->array = new T[this->element_count];
//...
else
{
this->array = new T[this->element_count];
}
}
should be
this->array = new T[this->element_count + 1];
//...
else
{
this->array = new T[this->element_count + 1];
}
this will fix the problems with allocation. That leaves us with _tempcpy() which fails because instead of trying to get the next element of the underlying array, it tries to do that with the double ptr itself. Read about operator precedence rules. Fixed version:
bool _tempcpy(T** src, T** dest, unsigned int count)
{
//....
for (unsigned int i = 0; i < count; ++i)
{
(*dest)[i] = (*src)[i];
}
//....
}
However, I am unsure as to why double ptr is needed in this function in the first place. Just use single pointers. Also dest should be const as it is not changing in this function. It gives the reader of the function a clear idea of which parameters will change inside the function and which will not:
bool _tempcpy(T* src, const T* dest, unsigned int count) {...}
same could be applied to other parts of the class.
Additionally, in C++
dyn_arr(void)
We don't do this. There's no need to explicitly write void. According to the C++ standard:
8.3.5 Functions [dcl.fct]
...
A parameter list consisting of a single unnamed parameter of non-dependent type void is equivalent to an empty parameter list.

Error reading characters of string . Allocate memory

i am using this codes.
Maybe it easy but now i can not. Please help me about this. I am looking always NULL in this function.
How can i solve this problem? I can not do it.
Thanks a lot.
Codes:
int my_len(const char* p) {
int c = 0;
while (*p != '\0')
{
c++;
*p++;
}
return c;
}
String::String()
:m_str(NULL)
{
}
String::String(char * other_str)
{
}
{
int mystrlen = my_len(m_str);
int myrhslen = my_len(other_str.m_str);
if (mystrlen != myrhslen)
{
return false;
}
else
{
for (int i = 0; i < mystrlen; i++)
{
if (m_str[i] != other_str.m_str[i])
{
return false;
}
}
return true;
}
}
}
Your non-default constructor has an empty implementation:
String::String(char * other_str)
{
}
So here m_str is left uninitialized.
You could maybe copy the string, if that is your intention like so:
String::String(char * other_str)
{
m_str = strdup(other_str);
}
But then you will have to manage the memory allocated by strdup yourself, e.g. in the destructor:
String::~String()
{
if (m_str != NULL)
free(m_str);
}

Destructor in C++ doesn't work

Can anyone tell me what's wrong with me destructor ? If I remove it all working well.
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <conio.h>
class DynString
{
private :
char *string;
int size;
public :
DynString(const char *tab)
{
string = new char[strlen(tab)];
size = strlen(tab);
if (string != NULL)
{
strcpy(this->string, tab);
}
}
DynString(const DynString& s)
{
string = new char[s.size];
if (string != NULL)
{
strcpy(string, s.string);
size = s.size;
}
else size = 0;
}
int Size() const
{
return size;
}
const char* CStr()
{
return string;
}
DynString& operator +=(const char* tab)
{
char *bufor = new char[size + strlen(tab)];
if (bufor != NULL)
{
strcpy(bufor, string);
strncat(bufor, tab, strlen(tab));
string = new char[strlen(bufor) + sizeof(char)];
}
if (string != NULL)
{
strcpy(string, bufor);
size = strlen(string);
}
return *this;
}
DynString& operator !()
{
unsigned int size = strlen(string);
for (unsigned int i = 0; i < size; i++)
{
if (string[i] >= 97 && string[i] <= 122)
{
string[i] -= 32;
}
else if (string[i] >= 65 && string[i] <= 90)
{
string[i] += 32;
}
}
return *this;
}
~DynString();
};
DynString::~DynString()
{
if (size == 0)
{
delete string;
}
else
{
delete[] string;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
DynString string("Test words.");
printf("String %s\n", string.CStr());
printf("Characters: %i\n", string.Size());
DynString copy = string;
printf("Copy %s\n", copy.CStr());
printf("Characters: %i\n", copy.Size());
copy += " - first fragment -";
copy += " second fragment.";
printf("Copy %s\n", string.CStr());
printf("Characters: %i\n", string.Size());
printf("Copy %s\n", copy.CStr());
printf("Characters: %i\n", copy.Size());
!string;
printf("String %s\n", string.CStr());
printf("\nEnd.");
_getch();
return 0;
}
You should define your destructor in the following way:
DynString::~DynString()
{
delete[] string;
string = nullptr;
}
However, I would not stick with manual memory management and use smart pointer instead.
Your destructor shall be:
if(string!=NULL)
{
delete[] string;
}
Or just
delete[] string;
(given that delete[]ing a NULL pointer is safe).
Remember: everything allocated with new[] must be destructed with delete[]; everything allocated with new must be destructed with delete.
EDIT:
Also, you should allocate string with strlen(tab)+1 space, to accomodate the terminating null byte (for the copy constructor, this means s.size+1).

std::vector::resize results in a crash in a template class

Here's the code :
The place where it crashed is marked with a comment(//////crash).
I don't know what results in the problem.
After I print the size of data got from file,It shows '1' means that the array should only contains 1 element. So it seems that there's no 'bad_allocate error' ...
Could you guys help me ? I would appreciate your kindly help very much. :)
#include<stdio.h>
#include<iostream>
#include<string>
#include<map>
#include<vector>
#include<algorithm>
#include<string.h>
#include<type_traits>
using namespace std;
bool read_int(int& val,FILE*& fp)
{
if(fp == nullptr)
return false;
fread(&val,sizeof(int),1,fp);
return true;
}
bool write_int(int val,FILE*& fp)
{
if(fp == nullptr)
{
return false;
}
fwrite(&val,sizeof(int),1,fp);
return true;
}
struct SANOBJ
{
char path[128];
char nickname[40];
SANOBJ(const char* _p = nullptr,const char* _n = nullptr)
{
if(_p == nullptr || _n == nullptr)
*this = {};
int m = strlen(_p),n = strlen(_n);
if(m < 128) strcpy(path,_p);
if(n < 40) strcpy(nickname,_n);
}
~SANOBJ(){}
SANOBJ(const SANOBJ& other)
{
memcpy(path,other.path,sizeof(char) * 128);
memcpy(nickname,other.nickname,sizeof(char) * 40);
}
bool operator < (const SANOBJ& other) const
{
return string(path) < string(other.path);
}
bool operator == (const SANOBJ& other) const
{
return (strcmp(other.path,path) == 0);
}
};
template <typename source_type> //the 'source_type' type need to have the member 'int m_index'
class FrameQueue
{
public:
FrameQueue() //fill the 1st frame automatically
{
source_type new_node;
new_node.m_index = 0;
m_data.push_back(new_node);
}
FrameQueue(const FrameQueue& other)
{
m_data = other.m_data;
}
bool AddFrame(const source_type& other) // keeps an ascending order
{
int index = _binary_search(other);
if(index != -1)
{
return false;
}
m_data.insert(std::upper_bound(m_data.begin(),m_data.end(),other,
[](const source_type& a,const source_type& b)->bool const{return a.m_index < b.m_index;}
),other);
return true;
}
bool DeleteFrameByElemIndex(int elemIndex) //delete frame according to the index of frame in the queue
{
if(elemIndex < 0)
return false;
if(elemIndex >= m_data.size())
return false;
typename std::vector<source_type>::iterator it ;
it = m_data.begin() + elemIndex;
it = m_data.erase(it);
return true;
}
bool DeleteFrameByFrameIndex(int frameIndex)
{
source_type node = {};
node.m_index = frameIndex;
int index = _binary_search(node);
if(index == -1)
{
return false;
}
typename std::vector<source_type>::iterator it;
it = m_data.begin() + index;
it = m_data.erase(it);
return true;
}
bool Clear() // There would always be a single frame
{
source_type new_node = {};
new_node.m_index = 0;
m_data.clear();
m_data.push_back(new_node);
return true;
}
bool WriteFile(FILE*& fp)
{
if(fp == nullptr)
return false;
bool result = write_int(m_data.size(),fp);
if(result == false)
return false;
fwrite(&(m_data[0]),sizeof(source_type),m_data.size(),fp);
return true;
}
bool ReadFile(FILE*& fp)
{
if(fp == nullptr)
return false;
int data_size;
bool result = read_int(data_size,fp);
if(result == false)
return false;
if(data_size > 0)
{
m_data.resize(data_size);
fread(&(m_data[0]),sizeof(source_type),data_size,fp);
}
return true;
}
private:
int _binary_search(source_type target)
{
int l = 0,r = (int)m_data.size() - 1,mid;
while(l<=r)
{
mid = (l + r) / 2;
if(m_data[l].m_index == target.m_index)
{
return l;
}
if(m_data[r].m_index == target.m_index)
{
return r;
}
if(m_data[mid].m_index == target.m_index)
{
return mid;
}
if(m_data[mid].m_index > target.m_index)
{
r = mid - 1;
}
else
{
l = mid + 1;
}
}
return -1;
}
public:
vector<source_type> m_data;
};
template<typename source_type>
class UniqueSource
{
public:
UniqueSource(){}
~UniqueSource(){}
bool Add(const source_type& other)//return false when insert failed,otherwise return true
{
if(m_map_source_to_index.find(other) == m_map_source_to_index.end())
{
int map_size = m_map_source_to_index.size();
m_data.push_back(other);
m_map_source_to_index.insert(pair<source_type,int>(other,map_size));
m_result.push_back(map_size);
return true;
}
else
{
m_result.push_back(m_map_source_to_index[other]);
return true;
}
return false;
}
bool Delete(int elemIndex) // delete the elem by elem Index,If succeed ,return true,otherwise return false
{
if(elemIndex < 0)
return false;
if(elemIndex >= m_data.size())
return false;
typename std::map<source_type,int>::iterator mit;
typename std::vector<source_type>::iterator vit;
for(mit = m_map_source_to_index.begin();mit!=m_map_source_to_index.end();++mit)
{
m_map_source_to_index.erase(mit);
}
vit = m_data.begin() + elemIndex;
m_data.erase(vit);
return true;
}
bool Clear()
{
m_map_source_to_index.clear();
m_data.clear();
m_result.clear();
return true;
}
bool WriteFile(FILE*& fp)
{
if(fp == nullptr)
return false;
bool result = write_int(m_data.size(),fp);
if(result == false)
return false;
if(m_data.size() > 0)
fwrite(&(m_data[0]),sizeof(source_type),m_data.size(),fp);
result = write_int(m_result.size(),fp);
if(result == false)
return false;
if(m_result.size() > 0)
fwrite(&(m_result[0]),sizeof(int),m_result.size(),fp);
return true;
}
bool ReadFile(FILE*& fp)
{
if(fp == nullptr)
return false;
Clear();
int data_size;
read_int(data_size,fp);
if(data_size > 0)
{
printf("[%d]",data_size);
m_data.resize(data_size); /////////////////Crash!!!!!!!!!!!!
printf("Resize Ok\r\n");
fread(&(m_data[0]),sizeof(source_type),data_size,fp);
}
read_int(data_size,fp);
printf("[%d]",data_size);
if(data_size > 0)
{
m_result.resize(data_size);
fread(&(m_result[0]),sizeof(int),data_size,fp);
}
return true;
}
//private:
map<source_type,int> m_map_source_to_index;
vector<source_type> m_data;
vector<int> m_result; //the index I want
};
int main()
{
UniqueSource<SANOBJ> m;
SANOBJ t = {"123","456"};
m.Add(t);
printf("Added\r\n");
FILE* fp = nullptr;
fp = fopen("test.b","wb");
if(fp == nullptr)
{
printf("Failed...\r\n");
}
bool ret = false;
ret = m.WriteFile(fp);
if(ret)
{
printf("Writed!\r\n");
fclose(fp);
}
fp = fopen("test.b","rb");
if(fp == nullptr)
{
printf("Failed...\r\n");
}
ret = m.ReadFile(fp);
fclose(fp);
printf("Readed\r\n");
for(int i=0;i<m.m_data.size();i++)
printf("%s %s\r\n",m.m_data[i].path,m.m_data[i].nickname);
return 0;
}
*this = {} default-constructs a new SANOBJ instance and then assigns it to *this. This would normally be OK, but here you are calling it from the SANOBJ default constructor (making the logic being something like "to default-construct a SANOBJ, default-construct a SANOBJ and then assign its value to myself"), leading to infinite recursion and eventually a stack overflow.
Sidenote: The copy constructor is not needed.
Yes. The problem is is with *this = {}
If I were you, I'd rewrite SANOBJ constructor like this (this is a rough code and you may need to slightly modify it if you wish)
SANOBJ(const char* _p = nullptr,const char* _n = nullptr)
{
if (( _p != nullptr ) && ((strlen(_p) < 128)))
strcpy(path,_p);
if (( _n != nullptr ) && ((strlen(_n) < 40)))
strcpy(nickname,_n);
}
It'll resolve the problem.
Naturally, I don't play with *this (not this).
If you want to be sure that the member variables are empty (char path[128] and char nickname[40])
set at the beginning of the constructor something like:
path[0] = '\0';
nickname[0] = '\0';
Or use something like on constructor:
SANOBJ(const char* _p = nullptr,const char* _n = nullptr)
: path(), nickname()
{
}
But don't use *this= {}

Array implementation of stack

I wrote this program and it supposed to test for the correct use of the three grouping symbols "(",")";"[","]"; and "{","}". It is using the array implementation of the stacks and supposed to evaluate if it is good string or a bad string. For example: (a+b), [(a-b)+c] would be good and )a+b( etc. would be bad string. When i run the program i get only one error. I thought i am missing a semi-colon or something, but after looking through the code several time,i can't find it. Maybe i got tunnel vision. Can you please see what the problem here is? This is the error: project1.cpp:41: error: expected initializer before 'while'.
#include <string>
#include <iostream>
#include <stdio.h>
using namespace std;
const int DefaultListSize = 100;
typedef char Elem;
class Astack {
private:
int size;
int top;
Elem *listArray;
public:
Astack (int sz = DefaultListSize)
{size = sz; top= 0; listArray = new Elem[sz];}
~Astack() {delete [] listArray;}
void clear() {top=0;}
bool push(const Elem& item) {
if (top == size) return false;
else {listArray[top++] = item; return true;}}
bool pop(Elem& it) {
if (top==0) return false;
else {it = listArray[--top]; return true;}}
bool topValue(Elem& it) const {
if (top==0) return false;
else {it = listArray[top-1]; return true;}}
bool isEmpty() const {if (top==0) return true;
else return false;}
int length() const{return top;}
}; //end of class Astack
Astack s;
const string LEFTGROUP="([{";
const string RIGHTGROUP=")]}";
int main()
while (!EOF) {
while (!EOL) {
ch = getc();
if (ch == LEFTGROUP[0]) {
s.push(ch);
}
if (ch == LEFTGROUP[1] {
s.push(ch);
}
if (ch == LEFTGROUP[2] {
s.push(ch);
}
} //checking for openers
while (!EOL) {
ch = getc();
if (s.top() == LEFTGROUP[0]) {
if (ch == RIGHTGROUP[0]) {
s.pop();
}
}
if (s.top() == LEFTGROUP[1]) {
if (ch == RIGHTGROUP[1]) {
s.pop();
}
}
if (s.top() == LEFTGROUP[2]) {
if (ch == RIGHTGROUP[2]) {
s.pop();
}
}
if (!s.empty()) {
cout<<"Bad String."<<endl;
else {
cout<<"Good String."endl;
}
}
}
return 0;
You forgot a { at the beginning of int main(). You should also end with }
int main(){
//your while code
return 0;
}