It must be pretty simple but i am so numb right now to think clearly.
So this is a small part of my code everything works fine except this.
What i actually wanted to do is infile1.open(temp2->path); but it's not possible since temp2 is a string. So i want to put this string into a char array like char p[100] to use infile1.open(p). It compiles but after some seconds boom: Stack around p was corrupted
char p[100];
while( temp2 != 0)
{
stringToCharArray(temp2->path, p);
infile1.open(p);
checkingWords(infile1, stopWords, invertedIndex);
infile1.close();
temp2 = temp2->next;
}
void stringToCharArray(string s, char *c)
{
int i;
int size = s.size();
for( i=0; i<=size ; i++)
{
c[i] = s[i];
}
}
I believe you want std::string::c_str.
infile1.open(temp2->path.c_str());
(Be careful, this const char * is only valid until the next time you change something in the std::string you get it from, in this case temp2->path).
It looks like the main error with your existing code is for( i=0; i<=size ; i++) should be i<size. But let's not go into that in too much detail, as you shouldn't really do it this way anyway.
You can do it the easy way
infile1.open(temp2->path.c_str());
But your hard way should look like this
void stringToCharArray(string s, char *c)
{
int i;
int size = s.size();
for( i=0; i<size ; i++) // < not <=
{
c[i] = s[i];
}
c[size] = '\0';
}
Of course the hard way is going to fail if your string happens to be 100 characters or more.
You can simply do:
infile1.open(temp2->path.c_str());
The stack corruption occurs inside your stringToCharArray function.
for( i=0; i<=size ; i++)
//^^^should not reach size-1, equal redundant
Related
I have a List class for char arrays. And I want to push back N arrays from 'a' to 'a..a'.
char* x;
SList list;
for (unsigned int i = 1; i < n+1; i++) {
x = new char[i+1];
for (unsigned int j = 0; j < i; j++) {
x[j] = 'a';
}
x[i] = '\0';
list.push_back(&x);
}
But every time, x has the same address. And in result, my List object contains N pointers to the same address.
Is there a way to push back these arrays in loop with correct memory allocation?
Before asking found this question, but it doesn't provide a cool solution for my problem.
In each iteration of the loop x = new char[i+1]; returns a different address, which is stored in x. So the value of x changes in each iteration, yet, the address of x doesn't.
Did you mean
list.push_back(x);
to add the address of the newly allocated memory? Of course this would require you to change the type of list the a collection of char *.
It must be mentioned that dereferencing &x after x goes out of scope will lead to undefined behaviour, because x doesn't exist anymore. You fill list with dangling pointers.
Finally I'd like to mention that you could avoid the nasty manual memory management and simply use a std::vector<std::string>.
std::vector<std::string> list;
for (unsigned int i = 1; i < n+1; i++) {
std::string newString(i, 'a'); // string with i times 'a'
list.push_back(newString);
}
Ok. I found a pretty straightforward solution:
char** x = new char*[n];
SList sl;
for (unsigned int i = 0; i < n; i++) {
x[i] = new char[i+1];
for (unsigned int j = 0; j < i; j++) {
x[i][j] = 'a';
}
x[i][i] = '\0';
sl.push_back(&x[i]);
}
With having N addresses to store pointers to arrays. I can just add their addresses to my list object
I have a problem that my code
char* strdup(const char* s)
{
int n = 0;
for(; *s != 0; s++)
{
n++;
}
char* p = new char[n+1];
for(int i = 0; i < n; i++)
{
p[i] = s[i];
}
p[n] = 0;
return p;
}
int main()
{
const char* p = "testing";
char* p_copy = strdup(p);
std::cout << p << '\n' << p_copy << std::endl;
return 0;
}
doesn't work as intended.
I want to write a function which takes in const char* and copies it to a new allocated char memory. When it is done it should return a pointer to the char.
Now when I try it out my output is simply:
testing
thanks for any help in advance
Try not incrementing s before you start copying it to p. I notice that in your first for loop you increment s until it points at a null, and then later use that pointer value to start your string copy. No wonder you are getting a null string.
Here:
for(; *s != 0; s++)
You increment s. So it no longer points to the beginning of the input string. It points to the null terminator of the string. Then, here:
for(int i = 0; i < n; i++)
{
p[i] = s[i];
You try to copy n characters starting from the null terminator, and you end up reading past the end of the array which has undefined behaviour.
Solution: Make a copy of s for counting the characters:
const char* s2 = s;
for(; *s2 != 0; s2++)
Even better, you could refactor the length counting part into a reusable function called strlen.
Written code to find and remove the largest word in a string without the using of library functions. Everything works fine. But when I want to free memory, the result is negative (displays an empty line). If you remove the call to the memory release function, everything will work correctly, but there will be a leak of memory.
How do I fix it? Please help me.
#include <iostream>
using namespace std;
int length(char *text) // string length
{
char *begin = text;
while(*text++);
return text - begin - 1;
}
int size(char **text) // size of two-dimensional array
{
int i = 0;
while(text[i]) i++;
return i;
}
void free_memory(char **text)
{
for(int i=0; i<size(text); i++)
delete text[i];
delete [] text;
}
char **split(char *text, char delim)
{
int words = 1;
int len = length(text);
for(int i=0; i<len; i++)
if(text[i] == delim) words++;
char **result = new char*[words + 1];
int j = 0, t = 0;
for(int i=0; i<words; i++)
{
result[i] = new char[len];
while(text[j] != delim && text[j] != '\0') result[i][t++] = text[j++];
j++;
t = 0;
}
result[words + 1] = nullptr;
return result;
}
char *strcat(char *source, char *destination)
{
char *begin = destination;
while(*destination) destination++;
*destination++ = ' ';
while(*source) *destination++ = *source++;
return begin;
}
char *removeWord(char *in_string)
{
char **words = split(in_string, ' ');
int max = length(words[0]);
int j = 0;
for(int i=0; i<size(words); i++)
if(max < length(words[i]))
{
max = length(words[i]);
j = i;
}
int index;
char *result;
if(!j) index = 1;
else index = 0;
result = words[index];
for(int i=0; i<size(words); i++)
if(i != j && i != index)
result = strcat(words[i], result);
free_memory(words); // I want free memory here
return result;
}
int main()
{
char text[] = "audi and volkswagen are the best car";
cout << removeWord(text) << endl;
return 0;
}
In fact, this is C style programming - not C++. I see that your aim is to implement everything from scratch, possibly for practicing. But even then, your code is not designed/structured properly.
Besides that, you also have several bugs in your code:
result[words + 1] = nullptr; must be result[words] = nullptr;
You need result[i][t] = '\0'; after the while loop in split
delete text[i] must be delete [] text[i]
You cannot assign to your result pointer memory from words, then free it and then return it for use by the caller.
There is at least one further bug in the second half of removeWord. It would be tedious to try to understand what you are trying to do there.
You might want to start with a simpler task. You also should proceed step-by-step and check each function for correctness independently first and not implement everything and then test. Also take a look at the tool valgrind for memory checking - if you use Linux.
The way you free memory correctly is to use RAII:
Only use new and new[] in constructors
Pair those with delete and delete[] in the corresponding destructor
Use automatic storage duration objects as much as possible
If you are specifically not using std::string and std::vector etc, for reasons of learning pointers, you will end up writing some small number of classes that resemble string and vector and unique_ptr, and then you go about programming as if you were using the std versions.
You have two issues. First is that result is assigned to a memory location in words. Second, is that you're storing the result of strcat in words[i] which will likely not have enough room (see strcat documentation).
result = new char[len(in_string)+1]; // +1 for space for null char
// the old loop reversed the word order -- if you want to keep doing
// that, make this a descending loop
for(int i=0; i<size(words); i++)
if(i != j && i != index)
strcat(result, words[i]);
free_memory(words);
return result;
So that when you free words, what result points to is also free'd. You would then need to free your result in main().
int main()
{
char text[] = "audi and volkswagen are the best car";
char * result = removeWord(text);
cout << result << endl;
delete[] result;
return 0;
}
So i'm trying to write a function which would get input from keyboard and store it in the 2d dynamic array. n is the number of lines (tried with 1-4 lines), m is the number of characters per line (256 in my case). I've read plenty about dynamic arrays and the use of new and the code seems totaly fine to me, but i keep getting this error when i try to enter the text: Access violation reading location 0x00000000. Can't figure out why. Please help.
void KeyInput (char **string, unsigned int n, unsigned int m)
{
cout<<endl<<"Input from keyboard"<<endl;
string=new char* [n];
for(unsigned int i = 0; i < n; i++ )
string[i]=new char[m];
for(unsigned int i = 0; i < n; i++ )
gets(string[i]);
}
can you give more information on where you are getting the access violation? I tried the following code (Visual Studio 2010, Window 7 Professional) and did not get an error. Note that I did change the characters per line to 15 instead of 255 as I wanted to test boundary conditions without a lot of typing.
Your function seems to work fine on my machine, however you do have a latent buffer-overflow using gets as it does not check for the length of the string. Remember that gets will append a null-terminator for you, so if in your case you enter exactly 255 characters you will overflow your buffer by one.
void KeyInput(char** string, unsigned int n, unsigned int m);
int _tmain(int argc, _TCHAR* argv[])
{
char* strArray;
KeyInput(&strArray, 4, 15);
return 0;
}
void KeyInput(char** string, unsigned int n, unsigned int m)
{
string = new char*[n];
for(unsigned int i = 0; i < n; i++)
{
string[i] = new char[m];
}
for(unsigned int i = 0; i < n; i++)
{
gets(string[i]);
}
}
(also ignore the hideous _tmain and _TCHAR stuff, they are Windows idiosyncrasies :) ).
Finally, unless this is an assignment (or an exercise for self learning), do what 40two suggested and use STL to make your life easy.
Use a vector of strings, take advantage of the force that STL has (use the force Luke see code below how):
void KeyInput (std::vector<std::string>& str_vec, int const n)
{
std::cout << "\nInput from keyboard" << std::endl;
for (auto i = 0; i < n; i++) {
std::string tmp;
std::getline(std::cin, tmp);
str_vec.push_back(tmp);
}
}
Update or Why your C++ teachers are wrong:
void KeyInput(char ***string, unsigned int n, unsigned int m)
{
std::cout << "\nInput from keyboard" << std::endl;
*string = new char*[n];
for (unsigned int i = 0; i < n; i++)
(*string)[i] = new char[m];
for (unsigned int i = 0; i < n; i++)
std::gets((*string)[i]);
}
int main()
{
char **string = 0;
KeyInput(&string, 4, 100);
for (auto i = 0; i < 4; ++i) std::cout << string[i] << std::endl;
return 0;
}
You need triple pointers in order to pass the 2d array by reference and to be properly filled (OMG!!!).
The user can enter only limited length strings (e.g., 99) don't forget strings have one character at the end (i.e., '/0' the null character).
You have to take care of the memory allocated and deleted later in order to avoid memory leaks.
If you want to shoot your self in the foot continue to program like this.
char *stringmult(int n)
{
char *x = "hello ";
for (int i=0; i<n; ++i)
{
char *y = new char[strlen(x) * 2];
strcpy(y,x);
strcat(y,x);
delete[] x;
x=y;
}
return x;
}
I'm trying to figure out what the flaws of this segment is. For one, it deletes x and then tries to copy it's values over to y. Another is that y is twice the size of x and that y never gets deleted. Is there anything that I'm missing? And also, I need to figure out how to get algorithm performance. If you've got a quick link where you learned how, I'd appreciate it.
y needs one more byte than strlen(x) * 2 to make space for the terminating nul character -- just for starters.
Anyway, as you're returning a newed memory area, it's up to the caller to delete it (eek).
What you're missing, it seems to me, is std::string...!-)
As for performance, copying N characters with strcpy is O(N); concatenating N1 characters to a char array with a previous strlen of N2 is O(N1+N2) (std::string is faster as it keeps the length of the string in an O(1)-accessible attribute!-). So just sum N+N**2 for N up to whatever your limit of interest is (you can ignore the N+ part if all you want is a big-O estimate since it's clearly going to drop away for larger and larger values of N!-).
For starters delete[] x; operates for the first time round the loop on some static memory. Not good.
It looks like an attempt to return a buffer containing 2^n copies of the string "hello ". So the fastest way to do that would be to figure out the number of copies, then allocate a big enough buffer for the whole result, then fill it with the content and return it.
void repeat_string(const std::string &str, int count, std::vector<char> &result)
{
result.resize(str.size() * count);
for (int n = 0; n < count; n++)
str.copy(&result[n * s.size()], s.size());
}
void foo(int power, std::vector<char> &result)
{
repeat_string("hello ", 1 << (power + 1), result);
}
no need to call strlen() in a loop - only call it once;
when new is called no space is requested for the null-character - will cause undefined behaviour;
should use strcpy instead of strcat - you already know where to copy the second string and findig the end of string by strcat requires extra computation;
delete[] is used on a statically allocated string literal - will cause undefined behaviour;
memory is constantly reallocated although you know the result length well in advance - memory reallocation is quite expensive
You should instead compute the result length at once and allocate memory at once and pass the char* as an in-parameter:
char* stringMult(const char* what, int n)
{
const size_t sourceLen = strlen( what );
int i;
size_t resultLen = sourceLen;
// this computation can be done more cleverly and faster
for( i = 0; i < n; i++ ) {
resultLen *= 2;
}
const int numberOfCopies = resultLen / sourceLen;
char* result = new char[resultLen + 1];
char* whereToWrite = result;
for( i = 0; i < numberOfCopies; i++ ) {
strcpy( whereToWrite, what );
whereToWrite += sourceLen;
}
return result;
}
Certain parts of my implementation can be optimized but still it is much better and (I hope) contains no undefined-behaviour class errors.
you have to add one while allocating space for Y for NULL terminating string
Check the code at below location http://codepad.org/tkGhuUDn
char * stringmult (int n)
{
int i;
size_t m;
for (i = 0, m = 1; i < n; ++i; m *= 2);
char * source = "hello ";
int source_len = strlen(source);
char * target = malloc(source_len*m+1) * sizeof(char));
char * tmp = target;
for (i = 0; i < m; ++i) {
strcpy(tmp, source);
tmp += source_len;
}
*tmp = '\0';
return target;
}
Here a better version in plain C. Most of the drawbacks of your code have been eliminated, i.e. deleting a non-allocated pointer, too many uses of strlen and new.
Nonetheless, my version may imply the same memory leak as your version, as the caller is responsible to free the string afterwards.
Edit: corrected my code, thanks to sharptooth.
char* string_mult(int n)
{
const char* x = "hello ";
char* y;
int i;
for (i = 0; i < n; i++)
{
if ( i == 0)
{
y = (char*) malloc(strlen(x)*sizeof(char));
strcpy(y, x);
}
else
{
y = (char*)realloc(y, strlen(x)*(i+1));
strcat(y, x);
}
}
return y;
}
Nobody is going to point out that "y" is in fact being deleted?
Not even one reference to Schlmeiel the Painter?
But the first thing I'd do with this algorithm is:
int l = strlen(x);
int log2l = 0;
int log2n = 0;
int ncopy = n;
while (log2l++, l >>= 1);
while (log2n++, n >>= 1);
if (log2l+log2n >= 8*(sizeof(void*)-1)) {
cout << "don't even bother trying, you'll run out of virtual memory first";
}