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 8 years ago.
Improve this question
I am relatively new to C++, and I am attempting to read sequenceofchars from a text file into a char array that is dynamically allocated. My code is as follows:
while (file.get(c))
{
if (c =='\n')
continue;
char *temp = new char[i++];
arrayA = new char[i++];
arrayA[i] = c;
delete [] arrayA;
arrayA = temp;
}
And the text file format is as follows:
>NameOfChars
sequenceofchars
This is obviously horribly broken, but I've struggled to figure out the exact methodology one would use to go through this. I know about the Vector class, but I am unsure about how to go about using that if that is the preferred method for reallocating arrays on the heap. Any help would be greatly appreciated. Thank you.
I think you should definitely take a look at the vector class since it would make your code a lot cleaner. Here is a small (untested) code sample of how to use it:
#include <vector>
std::vector<char> my_vector;
while (file.get(c))
{
if (c =='\n')
continue;
my_vector.push_back(c);
}
For more information please check http://www.cplusplus.com/reference/vector/vector/push_back/
A raw array isn't dynamically allocated; hence using an STL container like vector would be better.
ifstream inf;
char c;
vector<char> charVec;
while (inf >> c)
{
charVec.push_back(c);
}
Related
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 2 years ago.
Improve this question
Hello guys so my question is can you help me to debug a simple c program with gcc and make it work?
The teacher gave me this code and I should debug it and make it work, i tried but without any help I can't do It.
I compiled it with g++ -g double_free.c -o double_free
The program crashes.
this is the code:
#include <stdlib.h>
#include <stdio.h>
#define ARRAY_SIZE 100000
int main(int argc, char* argv[])
{
int i, test=5;
int* buf = new int[100000];
for (i=0; i< ARRAY_SIZE; i++){
buf[i] = i;
}
int result = 0;
delete []buf;
printf("result: %d\n", result);
delete[] buf;
printf("test %d\n", test);
return 0;
}
Here's a laundry list of complaints I have about this code:
You delete buf twice. This is really the only item I can see that needs actual debugging. The fact that the name of the exercise is double_free is a dead giveaway to experienced coders that this is the issue.
On top of that:
You should either be a C coder or a C++ coder, not a C+ coder (that strange variant that doesn't appear to have fully made the transition). Other than code meant to compile in both C and C++ environments, there's no reason a C++ program should be using the legacy C headers and functions (such as stdio.h and printf).
You should use ARRAY_SIZE in all places where you need the size of that array, otherwise you risk changing it in one place and not the other.
Variables should be scoped as tightly as possible. In other words, get rid of the current i declaration and just use for (int i = ....
Neither result nor test are changed, nor is buf used for anything, so your entire program boils down to std::cout << "result: 0\ntest 5\n";.
There's little point to putting argv/c in your main declaration if you don't use them, just use int main().
It's a good idea to move away from raw pointers, and start using smart pointers - these can automagically deallocate themselves when they go out of scope, leading to easier memory management.
You used delete[] buf; twice.
Just delete it between both prints
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 5 years ago.
Improve this question
I have a structure like this
typedef struct {
string aPath;
string dPath;
string tmpPath;
int cSet;
int socket;
} threadParams;
And some variables like this
string dirPath = "./Maildir/";
string authPath;
string tmpPath = "~/tmpPath/";
Im trying to initialize structure and add some data like this
threadParams *tP = (threadParams*)malloc(sizeof(threadParams));
tP->aPath = authPath;
tP->cSet = cParam;
tP->dPath = dirPath;
tP->socket = commSocket;
tP->tmpPath = tmpPath;
When I run program with this code there is SIGSEGV signal while trying to execute this: tP->aPath = authPath; when i delete these string members of structure and keep just int variable its okay, everything works properly.
Can anyone tell me why is this happening and how to fix it? Thank you
when you allocate the structure, you are only allocating the size of the threadparams struct. The underlying strings are not being properly constructed. Internally, they are pointers to unallocated memory.
As stated previously, when creating a dynamic object, use 'new' this will allocate and properly construct the object and all object elements it contains.
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 6 years ago.
Improve this question
It's been a while since I have worked in C++, I am helping a friend.
Is there a way without pointers return number of lines to a const int for use in a for loop?
I know I can do it with pointers but he has not learned them in class yet and I am not morally allowed to teach him anything the professor hasn't.
Example:
int numLines = sizeOfFile(inputFile);
for(int i = 0, i < numLines; i++){
//code here
}
EDIT: my fault I was moving fast to code this thing. I am helping him today I want to have a finished project so I can work off of it while helping him. The reason I need a constant int is so I can set array to that size not just for a for loop. the array is the problem.
You can initialize a const int just the same as you would initialize a regular int. The difference with a const int is that you cannot re-assign after initialization.
const int numLines = sizeOfFile(inputFile);
for(int i = 0, i < numLines; i++){
//code here
}
In the simplest case you're just looking for the number of '\n' characters in the file.
So let's say that you've successfully opened the file to: ifstream pFile then you can use an istreambuf_iterator to count those:
const auto numLines = count(istreambuf_iterator<char>(pFile), istreambuf_iterator<char>(), '\n')
A couple comments here:
The this count operation will consume everything in pFile's buffer, meaning you'll need to call pFile.seekg(0, ios_base::beg)
Picking and choosing values to read from an ifstream indicates a bad smell in code. It's likely that the file format was improperly conceived, or that the program will subsequently need to re-stream the remainder of file contents. The 2nd option seems to be true in your case, as you seek to illegally set the size of an array with a value found at runtime:
The reason I need a constant int is so I can set array to that size
EDIT:
When you say you want to use numLines to "right an array"[sic], my assumption is that the only reason that you would have needed your array to be that size is that you're going to stream each line from a file into your container, that is you're going to stream the entire file once to calculate the size then stream the entire file again to populate your container. Here's what you should do instead:
vector<string> lines;
for(string line; getline(pFiles, line);) {
lines.push_back(line);
}
Now lines will contain your entire file, with each element being a line. If numLines would have been important to you, instead you can use size(lines).
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 8 years ago.
Improve this question
I wanted to create an array of a specific size using a variable, but allegedly the only way to do that is to use pointers.
int size = 5;
string* myArray = new string[size];
I now want to assign an element from this array to another variable, which I believe will only work through dereferencing. The following line of code doesn't work. How do I fix it?
string line;
myArray[0] = "Hello";
line = *myArray[0];
Edit:
I just want to clarify something: Using the normal "myArray[0]" code doesn't work either. It compiles, but causes a crash. Here's some more specific code regarding what I want to do.
void MyClass::setLine(string line)
{
myLine = line; /*This is a private variable in MyClass*/
}
///////////////
MyClass* elements = new MyClass[size];
elements[0].setLine(myArray[0]);
I want to assign the array element to a private variable from a class, but the program crashes when I try to assign the value to the private variable.
If you know the size at compile time, you can use a normal array. If you only know the size at runtime, you could still use a std::vector, which is far easier to use than manual allocation.
Anyway, if you really want to learn about pointers for array managing, keep in mind that the index operator is equivalent to addition and dereference, i.e. ar[i] is the same as *(ar + i). In other words, indexing is just dereferencing at an offset.
As such, no extra dereference is needed. Just drop the asterisk in the failing line.
Valid code will look like
string line;
myArray[0] = "Hello";
line = myArray[0];
By the way you could use class std::vector instead of the array if you are going to add or remove elements from the collection.
For example
std::vector<std::string> myArray;
myArrray.reserve( 5 );
myArray.push_back( "Hello" );
line = myArray[0];
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need to resize a dynamic array without losing data.
Like this:
double * pVecDin;//POINTER
int num_values = 2;
pVecDin = new double[num_values];
pVecDin[0]=5;
pVecDin[1]=6;
int new_num_values=4;
pVecDin = new double[new_num_values];
//Next I lost value of pVecDin[0] and pVecDin[1]
pVecDin[2]=8;
pVecDin[3]=9;
Do I need make an Auxiliar Dynamic Array to copy the old values?
Like:
int new_num_values=4;
double * pVecDin_aux; //POINTER
pVecDin_aux = new double[new_num_values];
pVecDin_aux = pVecDin;
for(int i=0; i < n; i++)
{
pVecDin_aux[i] = pVecDin[i];
}
Make a new, empty array with the new desired size.
Copy everything in the old array to the new array.
Delete the old array.
Assign the pointer of the old array to the address of the new array.
Or use a vector.
As nhgrif has mentioned, you need to make copy of the array.
There is another way if you can use malloc for memory allocation, then you can use realloc for resizing the array.
There are better ways as suggested by other like to use std::vector or list.