FAQ Database Discussion Community


How do I fix this memory leak in my resize array method?

c++,pointers,dynamic-memory-allocation
I've created a simple integer array class: #ifndef INTARRAY_H #define INTARRAY_H class IntArray { public: // Constructors / Destructor IntArray(); IntArray(int size); IntArray(const IntArray& rhs); ~IntArray(); // Methods int size(); void resize(int newSize); void print(); //Operator Overloads IntArray& operator=(const IntArray& rhs); int& operator[](int i); private: // Data Members int* mArray;...

Accessing a 3D array in C++

c++,multidimensional-array,segmentation-fault,dynamic-memory-allocation
I have a char*** and I dynamically allocate some memory to it. However, when I try to assign some values to it, I get segmentation fault. The size I am using is not too big. It works when I create char[768][1024][3] but doesn't work when I add this dynamically with...

free dynamic array memory error: _BLOCK_TYPE_IS_VALID

c++,dynamic-memory-allocation,dynamic-variables
I'm trying to free dynamic memory but I'm getting an error. I need some help pointing out which part of my code is causing the error. I have destructor to free two dynamic arrays. Removing the destructor I get not errors. Error: _BLOCK_TYPE_IS_VALID(pHEAD->nBlockUse) Scores Class: class Scores { private: int...

ownership of dynamic allocated memory

c,dynamic-memory-allocation
What is the ownership of the dynamic allocated memory? For example, in one program dynamic allocate memory like this: int main() { int * p = malloc(10 * sizeof(int)); return 0; } 1) if this program exit, then will the memory pointed by p be freed()? I think the answer...

shallow copy struct got weird result on Xcode

c,malloc,free,dynamic-memory-allocation,shallow-copy
the code here is a typical example for shallow copy, it ought to got the warning when running, but on my Xcode, its running well and result is hi,hihi,hi why? The code: struct pc { char *p; }; int main() { struct pc pc1; pc1.p = malloc(100); strcpy(pc1.p, "hi"); struct...

How will you free the memory allocated?

c,memory-management,malloc,free,dynamic-memory-allocation
I need to free some memory allocated on my program. Can I use something to clean the memory when I need it ? #include<stdio.h> #include<stdlib.h> #define MAXROW 3 #define MAXCOL 4 int main() { int **p, i, j; p = (int **) malloc(MAXROW * sizeof(int*)); return 0; } ...

Accessing char array inside struct showing out of bounds error

c,arrays,struct,malloc,dynamic-memory-allocation
I have the following C struct and using the function getPerson(void) that returns a pointer to my struct returns a pointer to a new struct using user input. The following code does not compile and it gives the following error: #include <stdio.h> #include <stdlib.h> typedef struct { char name[50]; int...

C Comparing 2 strings turned into memory allocation issue

c,string,dynamic-memory-allocation
Let me start off by saying, I do realize there are a lot of questions with the exact same title, but I didn't find what I was looking for in any of them. I tried to write the following code, in order to errorcheck the user's input, so he wouldn't...

Unsigned int array allocation

c++,arrays,memory,dynamic-memory-allocation
I cannot allocate memory for my 1D array in c++. I tried using malloc and new operator. merge has value 0 when I use malloc. In case of new operator I obtain exception std::bad_alloc at memory location .... data_length has value of 131596814. I have got 8GB ram and plenty...

What is the difference between the Destroy method and the Finalize method on a Delphi object?

delphi,destructor,dynamic-memory-allocation
What is the difference between the "Destroy" method and the "Finalize" method on a Delphi object? This page (and other sources) mentions the "Finalize" method of Delphi objects, but the Delphi reference page about object methods strangely does not mention it at all (and even stranger, Google doesn't provide any...

What is wrong with the function strtok()?

c,arrays,string,file,dynamic-memory-allocation
So, how it works? I've the following block of code; for (i = 0; i < N; ++i){ array[i] = malloc(M * sizeof(char)); fgets(buffer, M-1, fp); array[i] = strtok(buffer, "\n"); } If I execute printf("%s", array[i]); inside the for the strtok() works as I expected, but if I do for...

How to get around the dynamically allocated variables in a loop?

c++,for-loop,dynamic-memory-allocation
I am a beginner in C++. Now I have a question. In order to make my code work, I dynamically allocated 2 variables: one outside the loop, and the other inside the loop. Here is my code: /////////////////////////////////////////////////////////////////////////// Tree* tree0 = new Tree(); for (int i=0; i<1000; i++) { Tree*...

Thread '
' has overflowed its stack when allocating a large array using Box

rust,heap-memory,dynamic-memory-allocation
I'm trying to create fixed-size array in stack, but it shows stack overflow, then I change it to heap (it said to allocate in the heap we must use box), but it still shows an stack overflow. fn new_gap(gap: usize) -> usize { let ngap = ((gap as f64) /...

Will dynamic arrays in fields of Delphi objects be automatically deallocated/freed when the object is destroyed?

delphi,destructor,dynamic-memory-allocation,dynamic-arrays
If I have a Delphi object containing a field with a dynamic array (containing for example strings), as follows: TClassWithDynArrayField = class(TObject) public some_dyn_array : array of string; end; will this array (and/or the contents of it) be automatically deallocated/freed when the object is destroyed, or will I have to...

Does realloc() invalidate all pointers?

c,pointers,dynamic-memory-allocation,behavior,realloc
Note, this question is not asking if realloc() invalidates pointers within the original block, but if it invalidates all the other pointers. I'm new to C, and am a bit confused about the nature of realloc(), specifically if it moves any other memory. For example: void* ptr1 = malloc(2); void*...

dynamic memory struct: free() failed w/ invalid size

c,struct,free,dynamic-memory-allocation
I have a C program that allocates memory for a structure and then free it. However, when I try to free the char array inside the struct, I get invalid size/pointer error. I am sure the structure is working fine because I checked by print out the context inside the...

Dynamic Memory Allocation

c,malloc,dynamic-memory-allocation
How malloc() stores metadata? void* p; void* q; p = malloc(sizeof(char)); q = malloc(sizeof(int)); I know that the return value p[0] points to the start of allocated block of memory, than if I iterate and print p[-1], p[-2].... q[-1], q[-2].... or p[1], p[2], p[3], p[4].... or q[1], q[2], q[3], q[4].......

Access violation on try to fill dynamic array (large number of items)

c,arrays,pointers,malloc,dynamic-memory-allocation
I have the following C code: int dimension; double *AtS; ... AtS=(double*)malloc(sizeof(double)*dimension); for (i=0; i<dimension; i++) { AtS[i]=0.0; } While dimension is ~6-8 millions it works fine, but when it about 300 millions it fails with access violation. The following message in debug: Unhandled exception at 0x012f1077 in mathpro.exe: 0xC0000005:...

How to dynamically initialize array in “object oriented” C?

c,oop,dynamic-memory-allocation
In the code below, how and where do I dynamically initialize an array that is in the Class struct? For example, if I made it double *var instead, where does the malloc statement go? myclass.h #ifndef MYCLASS_H #define MYCLASS_H struct Class; struct Class *new_class(); void class_function(struct Class*,double); #endif myclass.c #include...

Difference between two methods of array pointer initialization

c,pointers,dynamic-memory-allocation,array-initialization
Please explain the difference between char* str = "Hello"; And char* str = {"Hello"}; ...

C++ Deleting a pointer to a object that contains another pointer

c++,object,dynamic-memory-allocation
Let's say class A { A* array; public: A (){ array= new A [4]; } ~A (){ delete array; } } How do we free an object if we create such an object on heap like A* object_ptr =new A(); I'm a bit confused about freeing a pointer that points...

Difference between an allocator and a built in array in c++?

c++,arrays,memory-management,dynamic-memory-allocation,allocator
I have lately been trying to create custom containers that are similar to some of the library containers (i.e vector, list). and while I was using an allocator to allocate dynamic memory I noticed that the idea behind allocators and built in arrays are the same. allocators reserve a certain...

Allocate and dellete array of pointers

c++,pointers,dynamic-memory-allocation
Given the following struct declaration: struct Student { char * name; float gpa; } Implement the following functions: Student ** createStudentList(char ** names, int size); The above function creates an array of pointers to Student objects dynamically. It allocates Student objects and set their name as the passed in “names”...

Char* Array Memory Leak

c++,arrays,memory-leaks,valgrind,dynamic-memory-allocation
I am having issues de-allocating memory that I used in my char* array. In my code snippet below, I am creating a char* array named input that holds pointers to single words at a time followed by a pointerNULL at the end of the array. This is the only time...

Assigning a value to a deallocated memory in C++

c++,dynamic-memory-allocation
I am learning c++ using tutorials from http://www.learncpp.com. In the lesson on Dynamic memory allocation with new and delete (http://www.learncpp.com/cpp-tutorial/69-dynamic-memory-allocation-with-new-and-delete/), it states: Similarly, when a dynamically allocated variable is deleted, the pointer pointing to it is not zero’d. Consider the following snippet: int *pnValue = new int; delete pnValue; //...

Understanding a deallocation error

arrays,fortran,dynamic-memory-allocation,intel-fortran
I wrote a small, simple code that replicates an error I get in another, much larger code: PROGRAM allocateBug IMPLICIT NONE INTEGER, PARAMETER :: Nx = 10 INTEGER, PARAMETER :: Ny = 20 INTEGER, PARAMETER :: Nz = 30 REAL, ALLOCATABLE, DIMENSION(:,:,:) :: a ALLOCATE(a(0:Nx-1,0:Ny-1,0:Nz-1)) a(Nx+2,:,:) = 0.4 PRINT*, "size(a)...

Why does deque::pushback fail to allocate when there is still memory available?

c++,dynamic-memory-allocation,deque
I'm running 64-bit Windows 7 on a machine with 16GB of RAM but when I execute the following code: #include <deque> #include <iostream> using namespace std; struct Packet { unsigned char* m_buffer; int m_bufferSize; public: Packet() : m_buffer(nullptr), m_bufferSize(0) { } Packet(const Packet& rhs) : m_buffer(new unsigned char[rhs.m_bufferSize]), m_bufferSize(rhs.m_bufferSize) {...

Why my implementation of sbrk system call does not work?

linux,malloc,system-calls,dynamic-memory-allocation,sbrk
I try to write a very simple os to better understand the basic principles. And I need to implement user-space malloc. So at first I want to implement and test it on my linux-machine. At first I have implemented the sbrk() function by the following way void* sbrk( int increment...

when you declare a static variable in c

c,arrays,pointers,malloc,dynamic-memory-allocation
when you are declaring static variables in C, say you wrote a program as such: int *c; void foo(){ c = (int *) malloc (10*sizeof(int)); c = &c[3]; *c = *&c[3]; } what does it mean to have *c? I mean I understand that * means that it points to...

Unable to properly free malloc of another malloc [duplicate]

c,malloc,free,dynamic-memory-allocation,calloc
This question already has an answer here: String assignment in C 4 answers Here's the snippet with issues. int main() { char** RESERV = (char**)malloc(sizeof(char*)*4); printf("%i, %i, %i, %i, %i", **RESERV, *RESERV, RESERV, &**RESERV, sizeof(char*)); int i; for(i = 0; i < 4; i++) { RESERV[i] = (char*)calloc(sizeof(char),16); RESERV[i][15]...

Call to malloc() causes unexplicable program crash

c,string,segmentation-fault,malloc,dynamic-memory-allocation
I'm having an issue where a call I'm making to malloc() causes my program to crash. Here's the code: void update_item(char *input, item_t *new_node){ int i, count, shelf, weight, price, quantity; char *name; char *specifier; char aisle[1]; count = 0; /*Find name of the new item and assign to the...

why i get same values inside hash table?

c,hash,structure,dynamic-memory-allocation
I created hash table to insert my values . But when I insert more than one value I got same values inside all fields . my code is here : create a structure for both user and hashtable struct UserNode { char *username; char *password; }; struct HashTable { int...

Strcpy just crashes the second time I use in the same context

c,string,segmentation-fault,dynamic-memory-allocation,strcpy
This code waits for a string entered by the user, then the program should sort it immediately in an pointer array. The problem is in the case cop<0. I don't know what's the problem with strcpy() . If anyone could help, I'll be thankful. Here is the code : #include...

How to make a new instance of a struct in c

c,struct,malloc,dynamic-memory-allocation
I am new to C and thus still working on learning the language. I have created a linked list struct in a header file and I am trying to create a new instance of this struct. I know in java you can use the new operator but how would I...

Word translator program based on string comparison - heap memory assertion fails

c,arrays,string,malloc,dynamic-memory-allocation
I made a program that reads from file english_dictionary.txt the 200 most frequently used words in the English language, and in foreign_dictionary.txt I put the translations of the respective words in a foreign language. The content of the .txt files is placed in two char * type array of 200...

How to allocate memory to struct pointer using malloc.h header?

c,pointers,struct,malloc,dynamic-memory-allocation
#include<stdio.h> #include<malloc.h> #include<stdlib.h> struct student { char name[25]; int age; }; int main() { struct student *c; *c =(struct student)malloc(sizeof(struct student)); return 0; } What is the wrong with this code? I tried times by alternating this code to allocate memory to struct pointer. But this error comes when compiling:...

Are new and delete still useful in C++14?

c++,c++11,new-operator,c++14,dynamic-memory-allocation
Given availability of make_unique and make_shared, as well as automatic deletion by unique_ptr and shared_ptr destructors, what are the situations (apart from supporting legacy code) for using new and delete in C++14?

How much space to allocate for printing long int value in string?

c,dynamic-memory-allocation
I want to store a long value (LONG_MAX in my test program) in a dynamically allocated string, but I'm confused how much memory I need to allocate for the number to be displayed in the string. My fist attempt: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> int main(void) {...

std::bad_alloc exception thrown when operator= method is called C++

c++,dynamic-memory-allocation,bad-alloc
I'm writing my very first class in C++, which is a polynomial, and I've come across a bad_alloc exception thrown when I perform P=Q; //(P,Q being polynomials) I suppose the fact that bad_alloc is thrown (and sometimes the process terminates with -1073741819 status) has little to do with the fact...

memory corruption error during allocation

c++,qt,heap-memory,dynamic-memory-allocation
my code in C++ using QT gives me memory corruption error when I go through this part of the code: for (int vid=0;vid<m_trajs.size();vid++) { QVector<int*> clusterIDs_foronevideo; for (int level=0;level<nbClusters.size();level++) { int* clusterIDs_atonelevel = new int [long_vals[vid]]; for (int ind=0;ind<stInd[vid];ind++) { clusterIDs_atonelevel[ind] = clusterIDs[level][ind]; } clusterIDs_foronevideo << clusterIDs_atonelevel; } m_clusterIDs <<...

how does int*& variableName work ?

c++,dynamic-memory-allocation
My professor gave us the following code but i don't fully understand how int*& works. My understanding is that the selectionSort function is passing back the address of the memory location where the array starts. void SelectionSort(int* nums, unsigned int N, int*& SortedNums); void SelectionSort(int* nums, unsigned int index); int...

Passing dynamic array of structs to GPU kernel

c++,cuda,structure,dynamic-memory-allocation
I try to pass my dynamic array of structs to kernel but it doesn't works. I get - "Segmentation fault (core dumped)" My code - EDITED #include <stdio.h> #include <stdlib.h> struct Test { unsigned char *array; }; __global__ void kernel(Test *dev_test) { } int main(void) { int n = 4;...

Assertion error when passing object by value — it is my copy constructor?

c++,vector,copy-constructor,dynamic-memory-allocation,assertions
everyone! I just finished writing a 2-D maze (Class is an ADT titled "Maze"--how original) that uses dynamic memory allocation. I'm passing the Maze to a method of another class I've entitled "MazeSolver," which uses recursion and backtracking to solve the maze. Good news is my code compiles wonderfully when...

Proper format when dynamically creating namedtuple

python,python-3.x,dynamic-memory-allocation,namedtuple
I have created a namedtuple and am using it for tracking individual datasets. When I add a new "data point" to the namedtuple, the print() function shows that I don't have the same exact information. Here is an example: from collections import namedtuple bbnr = namedtuple('bbnr', ['SN', 'ptr', 'type2']) DVCS...

Freeing specific element from dynamically allocated array of structs

c,struct,dynamic-memory-allocation,dynamic-arrays
I have a simple struct s_person and constructor(int number) that takes the number of s_person we want to construct and returns a pointer to it. In this example I have constructed 2 s_person, and assigned values to their attributes, name. And it works. #include<stdio.h> #include<stdlib.h> #define MAX_NAME 50 typedef struct...

Is dynamic memory allocation in C++11 thread-safe?

multithreading,c++11,dynamic-memory-allocation
Is allocation and deallocation of dynamic memory in C++11 thread-safe? In other words: Can threads use new and delete as freely as single-threaded code?

Dynamically allocate an array of structs with C++

c++,arrays,dynamic-memory-allocation,records
I am trying to dynamically allocate an array of records. When I run my program with ./a.out it appears to work fine but when I try and run the program inputing the data from a .txt file (./myProg < ) it repeatedly records the first line of text in the...

Heap Corruption Detected C++ Custom Vector

c++,vector,dynamic-memory-allocation
Hey I am rehashing through a few old projects in a class I took and as I'm redoing this project I keep getting this error when my clear() function is called in the driver, Heap Corruption Detected: after Normal block (#142) CRT detected that the application wrote to memory after...

Using malloc to allocated 0 bytes

c,malloc,dynamic-memory-allocation
So allocating zero bytes is ill-defined so I want to treat 0 bytes as a fail. Would this code do the trick #include <stdio.h> #incude "xmalloc.h" void *malloc_or exit(size_t nbytes, const char *file, int line){ void *x; //declarea void pointer if ((x = malloc(nbytes)) == NULL){ fprintf(stderr. " %s: line...

can we dynamically allocate memory for static variable in C?

c,dynamic-memory-allocation,static-variables
Is it allowed to dynamically allocate memory for static variable like this: #include <stdio.h> #include <stdlib.h> struct person { int age; int number; }; static struct person* person_p = NULL; int main() { person_p = (struct person*)malloc(10 * sizeof(struct person)); } The above code built, but is it really allowed...

What will cause fgets() to continuously wait for input?

c,fgets,dynamic-memory-allocation
I am trying to put together a program that will ask the user to enter song titles for a set list to be printed in a random order. The program uses fgets() to take in the song titles. It also uses memory allocation to put each song in. It is...

How to return dynamic object from operator function?

c++,operator-overloading,dynamic-memory-allocation,return-type
I am quite confused about this. How to return a dynamically allocated object from operator function? Consider following example: #include "stdafx.h" #include <iostream> #include "vld.h" using std::cout; class Point { public: Point(int x,int y) : a(x),b(y) { } Point() { } Point operator + (Point p) { Point* temp=new Point();...

Dynamic array of pointers

c,arrays,pointers,dynamic-memory-allocation
I have an array of pointers to strings. char **array; I declare it this way and not char *array[N] because this array won't have a static number of elements. Declaring the array this way, I will probably have to realloc the sizeof it every time I add a new element...

Pointer to an Array of String Pointers [closed]

c++,string,pointers,dynamic-memory-allocation,cstring
I'm working on a program that does the following: Takes in a user-inputted string Allocates an array char** wordArr of string pointers based on how many tokens (words) are present on the string. Traverses the string and changes each space to '\0' Points each wordArr pointer starting at index 1...

Dynamically allocate user inputted string

c,arrays,user-input,scanf,dynamic-memory-allocation
I am trying to write a function that does the following things: Start an input loop, printing '> ' each iteration. Take whatever the user enters (unknown length) and read it into a character array, dynamically allocating the size of the array if necessary. The user-entered line will end at...

Dynamic Array Allocation, pass by value, out of range

c,arrays,pointers,dynamic-memory-allocation
I have two questions about dynamic allocated array. I have looked up some similar questions but still didn't find the answer. Pass by value Basically, I write two functions, one for allocation and another for free memory. When I pass the array pointer by value, the allocation function didn't work...

How to allocate memory dynamically for a char array in C++?

c++,arrays,pointers,char,dynamic-memory-allocation
I am learning about dynamic memory in C++. What I learned as a standard way of allocating & deallocating dynamically for any data type is, for example, //For double, double* pvalue1 = nullptr; pvalue1 = new double; *pvalue1 = 17.3; delete pvalue1; //free up when I'm done BUT, for a...

Issue with dynamic memory allocation in C

c,malloc,dynamic-memory-allocation
I am trying to implement a sort function (counting sort, it is probably wrong): void countingsortmm(int* numbers, int len, int min, int max) { printf("Sorting %d integers with the min: %d and max: %d\n",len,min,max); int countLen = max-min+1; /* create an array to store counts for the occurences of a...

Malloc'ing pointer-to-pointer member of struct

c,pointers,struct,malloc,dynamic-memory-allocation
I'm trying to use a structure to hold a pointer to a data block that I change sometimes when a file is updated, the idea being to free the old data block, malloc a new one of the right size, and assign the pointer to pointer in the structure to...

Pointing to an array inside a struct that is inside another struct

c,arrays,struct,malloc,dynamic-memory-allocation
How can I access an array / other type of data that is inside of a struct which is inside of another struct. This is what Ive tried so far and its coming out as c is not declared. I know I can declare c as prod_t *c but it...

reading from txt file into dynamicly allocated

c,file-io,struct,dynamic-memory-allocation
I want to read some data from txt file and store it in s_person struct and than print it latter. Text file structure looks like this: john 43 23 steven 23 44 micheal 11 0 Variable array is for those 2 numbers next to name in txt file. #include<stdio.h> #include<stdlib.h>...

Failed to add a node to linked list

c,pointers,segmentation-fault,malloc,dynamic-memory-allocation
i make the changes but i cant add more than 2 nodes its will freez but if 1 or 2 node will work well what is the reason??? i gave_up i can do nothing for that This is my code till time #include <stdio.h> #include <stdlib.h> #include <ctype.h> struct info{...

C++ how to allocate memory to a pointer of a struct which is member of another second struct?

c++,pointers,memory,struct,dynamic-memory-allocation
This is the code: # include<iostream> #include<stdio.h> using namespace std; struct hub { int info; int info2; }; struct hub2 { hub *p; }; int main() { hub *pi; pi = new hub; // allocate memory for pi pi->info = 30; pi->info2 = 45; cout<<pi->info<<" "<<pi->info2; // shows 30 and...

Memory allocation on GPU for dynamic array of structs

c,struct,cuda,dynamic-memory-allocation
I have problem with passing array of struct to gpu kernel. I based on this topic - cudaMemcpy segmentation fault and I wrote sth like this: #include <stdio.h> #include <stdlib.h> struct Test { char *array; }; __global__ void kernel(Test *dev_test) { for(int i=0; i < 5; i++) { printf("Kernel[0][i]: %c...

How is the concept of garbage collection related to non OOP languages

c++,c,garbage-collection,dynamic-memory-allocation
When using a language like C++ without any automatic garbage collector I understand that you have to use destructors to clean up after your objects. But how is the notion of "cleaning up" related to non OOP languages. What is the standard way of cleaning up structs and built in...

Malloc Allocates Out of Bound Memory Address

c,string,segmentation-fault,malloc,dynamic-memory-allocation
I am have the below snippet of code which allocates the memory out of the bounds: char *str1 = (char *) malloc(sizeof(char) * BUF_SIZE); printf ("str1 = "); scanf("%s", &str1); int n = strlen(str1); Initially I was getting a Segmentation Fault in strlen(). After playing with gdb I came to...

Dereferencing pointer to incomplete type error for a structure member

c,arrays,struct,compiler-errors,dynamic-memory-allocation
I have checked the other questions with similar problems, but none of the solutions worked for my case. The problem in hand is, I am trying to create a stack with dynamic memory, using this struct: struct stekas{ int content; struct stekas *link; } *top = NULL; However, I'm running...

Why does returning a data structure rather than a pointer mess with the integrity of my data?

c++,xcode,visual-studio,pointers,dynamic-memory-allocation
I'm building a sparse matrix class that holds two arrays (row and column) of pointers to doubly linked lists (down and right). Sort of like this: rows c0123456789 o1 l2 u3 m4 A-->B--> n5 | | s6 | V 7 V D--> 8 C--> 9 Both arrays are initialized to...