problem about dynamic-allocation-Collection of common programming errors
iammilind
c++ size new-operator dynamic-allocation
Why is it not possible to get the length of a buffer allocated in this fashion.AType * pArr = new AType[nVariable];When the same array is deallocated delete [] pArr;the runtime must know how much to deallocate. Is there any means to access the length before deleting the array. If no, why no such API is provided that will fetch the length?
Soylent Green
java arrays list dynamic-allocation
Please the read the question instead of assuming this is a duplicate.In the codebase I am working on I have a list of Foo objects:private List<Foo> fooList;Could someone please explain to me the difference(s) between this line of code:Foo foos[] = fooList.toArray(new Foo[fooList.size()]);and this line?Foo foos[] = (Foo[]) fooList.toArray();
justin
rubenvb
c++ constructor heap new-operator dynamic-allocation
void fun() {A *a = new A; //Here A is a class } //a should be deleted in fun()’s scopeint main() {fun();return 0; }The object created exists on the free store and cannot be used by the main() function. The why should the objects be created on the free store. Yes we can pass the object reference to the main function but we can even pass a copy of the object(even when not created using the new operator). Then what’s the exact use of the new and delete operator?
Fiddling Bits
c malloc dynamic-allocation
I am trying to learn dynamic memory allocation and structures and I have some questions. First of all#include <stdio.h> #include <stdlib.h> #include <string.h>int main() {int *number;number = malloc(1*sizeof(int));int a;for(a=0;a<150;a++){number[a]=a;printf(“%d “,number[a]);}return 0;}In this sample I planned it to give me error. Because I allocated it to size of 1 integer, then I wrote it way too much integers. Shouldn’t it give me an error? Can you explain this with detai
Prashant Kumar
c++ arrays string dynamic-allocation
I’m trying to create a string array and use a pointer to modify it. I’m not sure how to declare the pointer since strings can vary in length, and I think this is what causes the error.My code looks something like this:#includes <string> #includes <iostream> using namespace std;string *users = NULL; int seatNum = NULL; cin >> seatNum; users = new string[seatNum]; string name; cin >> name; users[seatNum] = name;It throws me an Write Access Violation when I try to change its
StefS
c++ class object dynamic-allocation
This code is not written bt me! In the class WebServer we overload +=operator. The class uses dynamically allocated array of objects of type WebPage(another class, composition) defined as WebPage *wp;WebServer & operator +=( WebPage webPage ) { WebPage * tmp = new WebPage [ count + 1]; for (int i = 0; i < count ; i ++) tmp [i] = wp[i]; tmp [ count ++] = webPage ; delete [] wp; wp = tmp; return * this ; }So we create a new array of dynamically allocated WebPages with extra space for one ob
SSight3
c++ pointers dynamic-allocation
In writing a response, I wrote some code that challenged my assumptions on how const pointers work. I had assumed const pointers could not be deleted by the delete function, but as you’ll see from the code below, that isn’t the case:#include <new> #include <string.h>class TestA {private:char *Array;public:TestA(){Array = NULL; Array = new (std::nothrow) char[20]; if(Array != NULL){ strcpy(Array,”Input data”); } }~TestA(){if(Array != NULL){ delete [] Array;} }char * const GetArray(){
lloyd
c++ arrays pointers dynamic-allocation
Having a lot of trouble with this after sifting through many posts on here. Everything compiles but I get a crash right here during this function which should be dynamically allocating the addresses of one array into this array of pointers. I see one or two memory addresses posted so I’m not sure why it would be crashing during the middle of this.string *copyArray(string ptrArray[],int sizeArray){string **dynamString = new string*[sizeArray];int i;for (i=0;i<=sizeArray;++i){(*dynamString[i])
Hugo
c++ pointers delete segmentation-fault dynamic-allocation
I’ve noticed that every time I delete a node in my Binary Search Tree class, it simply replaces it with a 0. In other words, Let’s say I have a tree of nodes that when printed in pre-order traversal yields “5, 3, 4, 6.” Let’s say I call the remove function to remove 3 (all this function does is search along the tree until it finds the desired node and then calls delete on that node). When I print again using pre-order traversal what comes up is “5, 0, 4, 6.” From what I understand about delete,
WhozCraig
c arrays multidimensional dynamic-allocation contiguous
For a multitude of reasons, I’d like to allocate multidimensional arrays in contiguous chunks of memory. I can do this by allocating them manually, eg:t.versions=(char***)malloc(sizeof(char**)*4); t.versions[0]=(char**)malloc(sizeof(char*)*t.size*4); t.versions[0][0]=(char*)calloc(t.size*t.size*4,sizeof(char)); for (i=1; i<t.size*4; ++i) t.versions[0][i]=t.versions[0][i-1]+t.size; for (i=1; i<4; ++i) t.versions[i]=t.versions[i-1]+t.size;Among other benefits, this solution simplifies freein
Abhineet
c calloc dynamic-allocation
Possible Duplicate:How do I correctly set up, access, and free a multidimensional array in C? I am trying to dynamically allocate memory for a 2D array using calloc. The columns are fixed as 2 so its only the rows that are dynamic.Here is what I have been trying :unsigned int **pts, rows; int main(){//some codepts = (unsigned int **)calloc(2*rows, sizeof (unsigned int **));}//The code to access the array : for(k=1;k<=i;k++) { printf(“\nX%d=”,k); scanf(“%d”,&pts[k][0]); printf(“\nY%d=”,k)
LihO
c++ arrays malloc dynamic-allocation variable-length-array
What is the advantage of allocating a memory for some data. Instead we could use an array of them.Likeint *lis;lis = (int*) malloc ( sizeof( int ) * n );/* Initialize LIS values for all indexes */for ( i = 0; i < n; i++ )lis[i] = 1;we could have used an ordinary array.Well I don’t understand exactly how malloc works, what is actually does. So explaining them would be more beneficial for me.And suppose we replace sizeof(int) * n with just n in the above code and then try to store integer value
LihO
c++ arrays argument-passing dynamic-arrays dynamic-allocation
I am trying to pass an array of Student into the function processStudent(string myFilename, Student* myArray, int &mySize).But it is giving me different kind of errors.The Student() does nothing, but I tried to assign them some sort of value, it still give the exact same error message:In the main I have this:// Create an array of students, with the size of theMax (256) Student* arrayOfStudent= new Student[theMax];// An integer that will keep track of actually how many students // Because whe
Primoz ‘c0dehunter’ Kralj
c arrays pointers 2d dynamic-allocation
Why wouldn’t this work? I’ve reviewed my code several times and just can’t find what’s wrong.Thanks!void generateData(float** inData, int x, int y){inData[0][0]= 3000.0; // SEGFAULT }float** createMatrix(int x, int y){float** array= malloc(sizeof(float*) * y);for(int i=0; i<y; i++)array[i] = malloc(sizeof(float) * x); }int main(int argc, char** argv) {float** arr = createMatrix(100,2);generateData(arr, 100, 2);return(0); }
bcr
c malloc dynamic-allocation
I was curious whether there exists a dynamic memory allocation system that allows the programmer to free part of an allocated block. For example:char* a = malloc (40); //b points to the split second half of the block, or to NULL if it’s beyond the end //a points to a area of 10 bytes b = partial_free (a+10, /*size*/ 10) Thoughts on why this is wise/unwise/difficult? Ways to do this? Seems to me like it could be useful.Thanks!=====edit===== after some research, it seems that the bootmem allocator
iammilind
c++ syntax dynamic-allocation new-operator
Possible Duplicate:Do the parentheses after the type name make a difference with new? I saw someone uses the constructor like this:class Foo {public: Foo(); };int main(){Foo *f= new Foo; }what is the difference between Foo *f= new Foo; and Foo *f= new Foo(); ?
Wolfgang Skyler
c++ arrays delete dynamic-allocation
I’ve got a rather simple, though large, system setup. It stores it’s data in a void* array because the data it’s storing could vary between float or double depending on how much accuracy is needed.just doing delete [] data raises a warning: deleting ‘void*’ is undefined [enabled by default] using MinGW. And I’ve got another variable to tell me if data is a float* or a double*, but does it matter which I use?In other words, could I use the fallowing code without worrying about memory-leak’s, or o
Primoz ‘c0dehunter’ Kralj
c arrays dynamic-allocation
I want to do this but it doesn’t work. Is it possible to do it or do I have to declare A as double pointer float**? Note that I need an universal function for various array dimensions so I can’t change the function arguments.void func(float** arr, int x, int y){//access to arr[0][0] for e.g. causes SEGFAULT } … float A[2][2]={{1,0},{0,1}}; func(A, 2, 2);
Atrus
c++ segmentation-fault destructor copy-constructor dynamic-allocation
I know there’s a lot of similar questions out there, but I haven’t found anything that helps yet. I’ve been at this for several hours now and it’s driving me crazy. I get a segmentation fault when a destructor is called for a variable that was created by the copy constructor.//Copy Constructor Stack::Stack(const Stack &aStack) {size = 0; //this is incremented as new items are pushed onto the stack.cap= aStack.cap;items = new int[aStack.cap]();for (int i = 0; i < aStack.size; i++)this->
user837208
c segmentation-fault calloc dynamic-allocation
Here is my code:#include <stdio.h> #include <stdlib.h>int main(){ int n=10; char *s= calloc(2,sizeof(char)); sprintf(s,”%d”,n); printf(s); return 0; }The intent is to assing 2 digit number to a (char *). when I run the code, I get segmentation fault. Outout from valgrind is- ==18540== Command: ./test ==18540== ==18540== Conditional jump or move depends on uninitialised value(s) ==18540== at 0x366C06F397: _IO_str_init_static_internal (in /lib64/libc-2.5.so) ==18540== by 0x366C
dyxh
c string dynamic-allocation
I don’t understand how dynamically allocated strings in C work. Below, I have an example where I think I have created a pointer to a string and allocated it 0 memory, but I’m still able to give it characters. I’m clearly doing something wrong, but what?#include <stdlib.h> #include <stdio.h>int main(int argc, char *argv[]) { char *str = malloc(0); int i; str[i++] = ‘a’; str[i++] = ‘b’; str[i++] = ‘\0’;printf(“%s\n”, str);return 0; }
Jonathan Wakely
c++ dynamic-allocation
Consider below code:#include <iostream> #include <string>using namespace std;class A{ public: int x; public: A(){x=0;} void fun1(){ cout << “fun1 is called \n”; cout << “Address of this is ” << this <<endl; delete this; } void fun2() { cout << “fun2 called \n”; } ~A() { cout << “Object Destroyed” << endl; } }; int main() { A* ptr=new A; cout << “Address of ptr is ” << ptr <<endl; ptr->fun1(); ptr->fun2(); return(0); }T
meagar
c free variable-scope static-variables dynamic-allocation
The code is as follow :#include <stdlib.h>int num = 3; // Static external variable int *ptr = #int main(void) {int num2 = 4; // Automatic variableint *ptr2 = &num2;free(ptr); //Free static variablefree(ptr2); //Free automatic variablereturn 0; }I try to compile the above code and it works, I’m curious does the free() function able to free both the static variable and also automatic variable? Or basically it does nothing?
akraut
c++ memory-management delete dynamic-arrays dynamic-allocation
Assume the following code:int main(int argc,char * argv[]){int * ptr;ptr = 0; // tried also with NULL , nothing changesptr = new int[10]; // allocating 10 integersptr[2] = 5;ptr[15] = 15; // this should cause error (seg fault) – but it doesn’tcout << ptr[2] << endl;cout << ptr[15] << endl; // no error heredelete [] ptr;cout << ptr[2] << endl; // prints the value 5cout << ptr[15] << endl; // prints the value 15 }The result of the execution is:5
Anish Ram
c crash dynamic-allocation
I’m using Doug Lea’s malloc.c and malloc.h in the following code:#include <stdio.h> #include <string.h> #include “dlmalloc.h”#define USE_DL_PREFIXint main() {char *test = dlcalloc(5, 1);strcpy(test, “helloextra”); dlfree(test); /* Shouldn’t this crash? */printf(“%s”, test);return 0; }And test prints correctly! Can someone please explain? I’m thinking that I haven’t tuned this malloc right. Anybody had this problem before?I started using Doug Lea’s malloc after I
Qix
c++ memory initialization char-array dynamic-allocation
So this may seem like a widely-answered question, but I’m interested more in the internals of what exactly happens differently between the two.Other than the fact that the second example creates not only the memory, but a pointer to the memory, what happens in memory when the following happens:char a[5]; char b* = new char[5];And more directly related to why I asked this question, how come I can doconst int len = 5; char* c = new char[len];but notconst int len = 5; char d[len]; // Compiler error
Web site is in building