C++ :: Variable Inside A Class - How To Manage Memory Allocation
Jul 30, 2014
recently I developed a class header only in C++ to deal with byte arrays. Since I developed programs in other languages that had some libraries to dial with byte arrays, I developed one that the syntax is very similar to other languages.
Since I'm not very familiar with memory management, I was concerned about somethings I've read about (ex: memory fragmentation).
Here is a very simple example of my practice:
class ByteArray {
public:
ByteArray(size_t size) {
buffer = (int8_t*)malloc(size);
}
[Code].....
The class is intended to be used as part of comunication protocol in a webserver, byte arrays are created and destroyed a lot. Should I use pools? Is there a better practice? Am I doing everything wrong (laugh)?
For those who wants to see the entire class: [URL]
View 9 Replies
ADVERTISEMENT
Jun 27, 2013
The problem is the following, I am making a wrapper object of sockets in c++, since the ones in c are somewhat ugly, and not quite OOP. I can't use boost sockets since the project I am currently working on, can only use the libraries found in ubuntu 12.04 repositories, and the ubuntu 12.04 repositories are on boost-1.46. My solution was the following, three classes, AbstractSocket, ServerSocket, and Socket. AbstractSocket is the superclass of both ServerSocket and Socket. The following is the class definition of each of these classes:
class AbstractSocket {
public:
AbstractSocket();
AbstractSocket(const int file_descriptor, const struct addrinfo* local_address,
[Code].....
My problem and question is the following, on ServerSocket::accept method I have to do a "client_socket = new Socket(abstractSocket);", and in Socket::recv_all method I do something like "buffer = new unsigned char[bytes_to_receive];". These two situations are somewhat problematic to me, because I don't wish to make the caller of the methods responsible for deleting this memory.
Therefore, is there an elegant way to retrieve heap allocated space from a function/method? Or better yet, is there an elegant way of telling the caller of the method, that the memory will have to be deleted?
I thought of placing an "unsigned char* buffer" inside Socket class, and to delete the memory allocated in the destructor and on consecutive calls to recv_all, but i don't believe this is the solution, and it doesn't solves me the problem for the "accept" method.
View 3 Replies
View Related
Apr 17, 2014
I'm having problems with this code:
#include <iostream>
using namespace std;
class Foo {
public:
Foo( int n );// Constructor
~Foo();// Destructor
int *ptr;
int N;
[Code] ....
I'm using Visual C++ 2008 version. The problem arises at the end, after the sentence 'system("pause")' is reached, which makes me think that the problem happens when calling the destructor. The destructor is called twice, the first time it's called is in the function print. The problem seems to be that the destructor can only be called once.
I know I can avoid this situation by defining the function print like this:
void print ( const Foo &f )
...
but I would like to know if there is some way I can do this keeping the definition that I've provided.
View 2 Replies
View Related
Mar 31, 2013
Say I have a class with a few member functions, and only two data members: an int* Table; and an int Size;, to store the number of elements in Table.
I'm using a copy constructor that takes in two parameters: int* table, int size. In this case, is the address that table points to the same address as the object that table is part of? And furthermore, is it possible to say table.Size? I want to compare the passed array's size to the passed size.
View 2 Replies
View Related
Nov 9, 2013
I am trying to access a variable from another class through another class but it is not returning its "instance"?
Example:
Class View
Code:
...
V3D_Viewer viewer;
...
Class MainWindow
Code:
...
viewer* myView;
myView = new viewer();
...
Class Test
Code:
...
MainWindow window;
window.myView->setBackgroundColor(WHITE);
...
I am new to c++ references and pointers,
View 3 Replies
View Related
Dec 1, 2013
How can I add the variable adress to a void pointer inside of a class?
class variant2 {
private:
void *Vvariant=NULL;
public:
template<typename b>
variant & operator = (b *adress)
[Code] ....
if possible i want avoid the '&' when i assign the variable address.(variant2 f=varname;//like you see i don't use the '&')
for the moment i just need put the address to Variant pointer. but i receive several errors .
View 4 Replies
View Related
Nov 19, 2013
I wrote a class to manage pointers better (because I am making a large program and don't want to call a constructor on somthing that was already deleted... etc...), but I am getting some compiler errors. I'm not sure what to do.
here is the class prototype:
template<typename type>
class pointer_class{
public:
pointer_class() : dat(NULL), del(false) {}
explicit pointer_class(const pointer_class<type>& d) : dat(NULL),
[Code].....
View 19 Replies
View Related
Jul 14, 2013
I have declared a global variable as pointer. The program performs certain number of iterations. After every iteration, the size of memory required for the pointer changes and this pointer variable is to be accessed by different functions. Now, here is my doubt:If I allocate the memory for this global variable in a function, will the contents of the memory be lost once I exit that function. In my opinion, it should not be the case as the dynamic memory allocation takes place in "heap" and should not be affected by the call of functions.
View 4 Replies
View Related
Oct 17, 2014
Code:
int *p, ar[100];
p = (int *)malloc(sizeof ar);
.. *p is a pointer variable, but what means another * here --> (int *)?
View 3 Replies
View Related
Jan 21, 2014
I am trying to allocate a memory to vector but while running the program,my window appear and PC get halt state then i have to force fully shutdown my PC I found that due to the vector i am getting this problem.
#define SCOPEPLOT_MAXNUM_SAMPLES (1000000)
QHash<int, std::vector<double>*> m_sampleHash;
m_sampleHash.insert(1, new std::vector<double>(SCOPEPLOT_MAXNUM_SAMPLES));
std::vector<double>* vec_p = m_sampleHash.value(1);
for(int k = 0;k < numSamples;k++)
{
count++;
vec_p->at(k) = data_p[k];
}
View 5 Replies
View Related
Apr 15, 2014
vector<Type> vect; //allocates vect on stack and each of the Type (using std::allocator) also will be on the stack
vector<Type> *vect = new vector<Type>; //allocates vect on heap and each of the Type will be allocated on stack
vector<Type*> vect; //vect will be on stack and Type* will be on heap.
What I would like to know is, are all of the above statements true?
View 3 Replies
View Related
Jul 13, 2014
1) int *a=new int[10]
2) int a[10]
What are the exact differences in these two types of methods of allocating memory for an array ? When does 1st method is useful and when does 2nd ?I also read somewhere that in Ist method memory is allocated from heap but i don't know from where memory is allocated in 2nd method and what difference these memory allocations causes.
View 3 Replies
View Related
Dec 18, 2013
Here is my code:
Code:
class Base {
};
class Derived1 : public Base {
};
class Derived2 : public Base {
} class Bar {
public:
void SomeFunc();
[code].....
MSVC2010 throws out compiler error which says:
Code:
no operator found which takes a right-hand operand of type 'Derived *' (or there is no acceptable conversion)
What I don't understand is why? The pointer is an address of 0 element of an array. So what is the problem? I can eliminate the error by using double pointer but it will be an overkill.
View 8 Replies
View Related
Feb 24, 2014
I have recently bought a copy of "Jumping into C++" and have come to chapter 14 ( dynamic memory location) and have a question.
On page 153-154 an example of dynamic allocation is given for array's of int. How would the code look like for strings or structs ?
The allocation was given by:
Code:
int *growArray (int* p_values, int *size)
{
*size *= 2;
int *p_new_values = new int[ *size ];
for ( int i = 0; i < *size; ++i )
{
p_new_values[ i ] = p_values[ i ];
}
delete [] p_values;
return p_new_values;
}
Sample Code I tried to use this for an array of structs but failed completely....
I used the following struct Code:
struct user{
int days;
string name;
};
and the allocation function (which does not work):
Code:
struct user *growarray (struct user *p_values, int *size) {
*size *= 2;
struct user *p_new_values = new struct user[ *size ];
for ( int i = 0; i < *size; ++i )
[Code].....
View 8 Replies
View Related
Jul 3, 2013
I am creating a connect 4 game using dynamic memory allocation the question is;
Write a two-player game of Connect Four where the user can set the width and height of the board and each player gets a turn to drop a token into the slot. Display the board using + for one side, x for the other, and _ to indicate blank spaces.
I have created the board. However I am unsure as how to make a start on getting the players to make moves.
Code:
#include <iostream>
using namespace std;
char **create_table(int width, int height, char blank) {
char **p_p_connect4 = new char*[height];
for(int i = 0; i < height; i++) {
p_p_connect4[i] = new char [width];
[Code]....
View 1 Replies
View Related
Jul 11, 2013
Small code to show overflow...But when I compile and run - buffer_one is not being overwritten when the byte size of buffer_two overflows .
Code:
#include <stdio.h>#include <string.h>
int main(int argc, char *argv[]) {
int value = 5;
char buffer_one[8], buffer_two[8];
strcpy(buffer_two, "two"); //Put "one" into buffer_one
strcpy(buffer_one, "one"); //Put "two" into buffer_two
}
[code]....
View 3 Replies
View Related
Dec 27, 2014
I've been working on a matrix class and I ran into a problem in writing my matrix class. I keep getting 0 as a determinant and with some debugging, I found that I was losing allocated data or something similar. This algorithm I'm pretty sure works because I used this same algorithm in a function I made in python. [URL] .... That's where I found the algorithm.
/*template <class T>
double Matrix<T>::det(T* array, size_t dim, bool recursion)*/
double det(T* array = NULL, size_t dim = 0, bool recursion = false) {
if (recursion == false) {
if (m != n) {
return 0;
[Code] .....
View 2 Replies
View Related
Aug 7, 2013
I'm about to solve least-squares problems within a C++-Program. (Equations like inverse(transpose(A)*A) * b and so on)
So I use cmatrix as library and there is the following problem:
#include <cmatrix>
typedef techsoft::matrix<double> dMatrix;
dMatrix A(nDataPoints, numCol);
dMatrix z(numCol, 1);
dMatrix b(nDataPoints, 1);
dMatrix (nDataPoints, nDataPoints);
nDataPoints and numCol are globally defined integers which get the values 120 and 13 (just about the size of those matrices).
So, A is not a problem but as soon as it gets to z and b there is a dialog "Out of Memory" and it stops at the line
return HeapAlloc(_crtheap, 0, size ? size : 1);
(in malloc.c).
This program debugged without any problem with same code - now I just edited the size of the matrices. And I tried the same with another library called "Eigen" and I get the same problem - so I guess there is a problem with the heap and I have to do some kind of memory allocation...
View 4 Replies
View Related
Nov 17, 2013
I am fairly new to dynamic memory allocation and I keep getting a segmentation fault in this code of mine. This is what the method should do:void sort StringsByReversePoints(char **myWords): This function sorts the char* values (i.e. strings) of myWords in descending order of point value by calling getWordPoints as a helper function and comparing adjacent words. This simple (but inefficient) sorting algorithm starts at the beginning of myWords array and sweeps to the end comparing adjacent values and swapping if they are out of order. After N (length of the array) sweeps the array is fully sorted. Note that efficiency can be improved by a factor of 2 by shortening each successive sweep by one, since the first sweep will have guaranteed the minimum point value word is the last element of the array, the next sweep guarantees the last two elements are correct, and so on....Additionally, if a given sweep results in zero swaps then the array is sorted and you can return immediately.
View 5 Replies
View Related
Nov 16, 2013
we are currently covering double pointers and memory allocation. Currently getScrabbleWords is not working. when I compile with commented code (Main() works fine) I get a segmentation fault.
This is the purpose of getScrabbleWords:
char **getScrabbleWords(char **allWords, char letters[]):
This function takes an array of char* values (i.e. strings) representing all the words read from wordlist.txt. Each of these words is tested by callingcanWeMakeIt as a helper function, and pointers to the words that can be made are put into an array, myWords. Note, copies of the words are not made! In order to indicate the end of myWords, we terminate with a NULL pointer. Thus, if N words can be made from letters then myWords should have length N+1.
View 6 Replies
View Related
May 5, 2013
Why cant a dynamic memory allocation work with references? I was told that references work with const pointers deep down so shouldn't this be legal code?
int &&a=new int;
My compiler says that a entity of int* cannot be used to initialize a entity of int&&?
Does that mean that the compiler thinks of them as different types except deep down a reference is implemented with a pointer? Is this right?
View 14 Replies
View Related
Feb 13, 2013
I am using a pair of pthreads that call a pair of functions for ping-pong dma data transfer that are used in a loop for data transfer from an acquisition board. For a large # of waveforms, I ultimately run out of PC memory and the program stops. At the end of each function I use the delete[] command to clear memory for reuse, but the pointer appears to advance by the array size used for the transfer until the location exceeds the 2 GB I have for memory. I can see this happening using the Task Manager performance button time plot and window of total memory used continuing to increase to the limit. The culprit for one of the functions (2nd) is:
unsigned char* dataBuffer2 = (unsigned char *) (pci_buffer2.UserAddr);
where pci_buffer1 and 2 have been set up and allocated in main. I also had the following line in each function process:
double* Rin = new double[length];
and it used up memory twice as fast. When I transferred the last line to an area just prior to main and used a constant 1024 for length, the program ran twice as far before exceeding system memory, so it appears that both lines were forcing new memory assignments and moving the pointers accordingly. In addition to using the delete[] command to free memory unsucessfuly at the end of each function procedure, I ended up closing the memory at the end of each procedure, then reallocating it again with the idea that the pointer would be set back to the original value, but it still seems to icrement along. So, neither approach appears to allow reuse of the memory because the pointer continues to march along. Using Visual C++ 6.0 to compile.
View 1 Replies
View Related
Jun 17, 2013
This is the question; Write a function that builds a two-dimensional multiplication table with arbitrary sizes for the
two dimensions.
This is what I have done. I have allowed the user to input whatever size table they want by arbitrarily choosing what value they can input. However I cannot get the board to have blank squares. I thought the char would do it.
Code: #include <iostream>
using namespace std;
char SQAURE_CHAR = {' '};
const int Board_Size = 14;
[Code] ....
View 3 Replies
View Related
May 23, 2013
Suppose I wished to reallocate memory (resize) an array of pointers. Why does the following not work?(The program runs, yet yields a faulty segmentation error message. Why?):
Code: char **ptrarr = (char**) malloc(sizeof(char*))
Code: ptrarr = (char**) realloc(ptrarr, (capacity) * sizeof(char*));
View 14 Replies
View Related
Dec 21, 2014
I need to use dynamic memory allocation and use pointers to iterate through the arrays that I have already in this program. I am lost, nothing I do works and where to use the pointers. I am just looking for a push in the right direction so I can finish this project and how I can implement pointers in my program.
#include <iostream>
#include <string>
#include <cstdlib>
#include <iomanip>
#include <stdio.h>
using namespace std;
[Code]...
View 1 Replies
View Related
May 19, 2014
I am working on an OOP assignment (text handler) which part of its description is:
Some lines of text as a story which the delimiter between each story is %%%%%
Each text loaded should only occupy the space needed for the text to fit.
It's required to use dynamic variables of type char*. To be more detailed, the text-handler must contain a vector of such char-pointers (i.e. c-strings), and the parameter in the constructor indicates how many pointers (c-strings) to be contained in the vector. Each loaded text will be represented by a number, so that the first text in the file gets number 0 and the next one gets number 1 ... etc. When you want to access a text, you request the text with a certain number, and then get a pointer in return that may be used to output the text on the screen.
My problem is first to allocate a dynamic memory like char** without defining the number of array elements (Each text loaded should only occupy the space needed for the text to fit. )and then store each story from text file (comprise of a few lines of text) into that dynamically located memory(char **)to be able to do some operation on it later.
View 15 Replies
View Related