C :: Malloc Memory Allocation?
Oct 17, 2014Code:
int *p, ar[100];
p = (int *)malloc(sizeof ar);
.. *p is a pointer variable, but what means another * here --> (int *)?
Code:
int *p, ar[100];
p = (int *)malloc(sizeof ar);
.. *p is a pointer variable, but what means another * here --> (int *)?
I am writing a very basic database in C++ and I am accessing the data from a web browser. I am using the opensource Mongoose web server code....
I have an issue...
The way the DB works is this: on starting, the DB loads a json file of all of the data into it. I have a class called DatabaseLoader that does this - it is the class that gets rewritten depending on the data structure of the json.
This is passed to vectors (vector<Node*> and vector<Edge*>) as references from Graph object.
Once the DatabaseLoader has finished it can be destroyed and any memory allocated objects it created (except the ones in those two vectors).
From then on, the Graph object is in charge of all of the elements in the database that are stored in the two vectors. When the user browses to htpp://127.0.0.1:8000 they see the json representing each object in the vectors.
All good so far....
However, when I repeatedly hit refresh in my browser (and call me insane...) at quite a fast speed I get this error:
Code:
main(29855,0x7fff76763310) malloc: *** error for object 0x7f98b2829408: incorrect checksum for freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug
[1] 29855 abort ./main testing.json
It seems to me this would be if I tried to "delete" and object twice, or if one of my objects was overwriting memory somewhere. However I am not recreating anything, I am just looping over the vectors and printing out the content. When I refresh slowly, I dont see this happen - i did it quite a lot of times, but when I do it fast I think it is happening.
So is there any possibility of me hitting the c++ web server to quickly and it is trying to process the data twice, causing some sort of memory error - i.e do I need to implement threading or something??
I can paste code, but there is quite a lot now....
does memory reserved by malloc() get freed when the function it is called in finishes?
View 6 Replies View RelatedThere is a part in the lesson that explains how malloc is used to allocate free memory to a pointer and gives us 2 examples:
Code:
float *ptr = malloc( sizeof(*ptr) ); and Code: float *ptr;
ptr = malloc( sizeof(*ptr) );
From my logic in the first case we allocate the memory to *ptr and in the second to ptr.
It's a bit confusing, am I missing something?
How can I view the number of bytes that have been allocated by using the malloc function?I tried:
mem = (float*)malloc(num*sizeof(float));
printf("The amount of memory allocated using malloc is %d.", mem);
Note: The variable "num" in my program is equal to 7.But every time I run the program, this value changes.
Consider this program:
Code:
// sb_string class v1.04
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct sb_string {
[Code] ....
And here is the output I got:
Code:
[harshvardhan@hari-rudra] ~/Desktop% gcc49 -o test test.c
[harshvardhan@hari-rudra] ~/Desktop% ./test
-before Value of len = 1
(in_function)-before Value of len = 1
(in_function)-after Value of len = 1
-after Value of len = 1 I was trying to make a little easier to work with string. Once the memory is allocated by malloc via sb_init() function, the sb_massacre function wasn't working to deallocate the memory. I had used multiple versions of gcc and clang but the result is same.
I have a question about the KLU library for LU factorization of sparse matrices. The KLU library accepts a pointer to a memory allocator function, by default it is malloc(). Then it uses this pointer to allocate the memory required.
I want to extend the library and I now have object of classes. I want to use the operator new instead of malloc to allocate the memory. In the same time I want the new operator to call the constructors of the objects. Is there a way to do it?
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 RelatedI 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];
}
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?
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.
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.
What is wrong with my function why does it spit out huge numbers? And how do i use malloc or calloc to create an array in dynamic memory, and return a pointer to this array
Code:
#include <stdio.h>#include <stdlib.h>
int fibonacci(int n)
{
int i;
long int fib[40];
fib[0]=0;
fib[1]=1;
for(i=2;i<n;i++){
fib[i] = fib[i-1] + fib[i-2];
[Code]....
My application calls malloc in multiple subroutines, finally releasing all using free. This is done using my zalloc library (see my other post: [URL] .....
Somehow, when the applications tries to detect the available ammount of memory at the end of the test (allocating, freeing, testing), the freemem function gives me about 4-6MB less memory than at the start of the test? (out of 21MB available on the device at the start).
All memory is allocated and freed using the malloc/free routines within the library, with the exception of the SDL functions, which are registered externally on allocation and release.
When does malloc() return null ? I want to allocate a big virtual memory which can not possibly fit on RAM, so most of it will be stored on disk. I am going to access the data sequentially so at any one time the data I am working on will fit in RAM. So I am hoping the OS will move the required pages in and out of disk. I can achieve this behavior manually by allocating the required blocks on RAM but this is rather tedious. Say I have an array a[100][10000000000]. At any one time I am working only on a[i-1][], a[i][], a[i+1][] which can fit in RAM but not the whole array. So how do I allocate the array so that I can work on it using for loops for(i=0;i<100;i++) without handling the page movements myself?
View 2 Replies View RelatedI 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].....
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]....
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]....
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.
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] .....
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...
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 Relatedwe 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.
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?
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.
I have a program which call only one time malloc at the start of the program. When running, I see with 'process-explorer.exe' that memory is growing in little steps. Is this normal? why?
Using Windows 7