FAQ Database Discussion Community


Is there a better way to do this than writing a wrapper allocator that stores a reference to a stateful allocator object?

c++,memory-management,lambda,allocator,std-function
For example: struct Foo { MyPoolAlloc<char> pool; std::vector<int , MyPoolAlloc<char>> vec_int; // The wrapper allocator would replace MyPoolAlloc<> here. std::vector<std::function<void()> , MyPoolAlloc<char>> vec_funcs; // The wrapper allocator would replace MyPoolAlloc<> here. Foo() : vec_int(pool) , vec_funcs(pool) {} // I want to store lambdas with captured variables using the custom allocator...

Using parse.com and having allocation memory issue

android,memory,memory-management,parse.com,allocation
I'm new to programming, I've been making an app for the last 3 months and learned a few things. But I haven't come across to how to solve this issue. I've been using Parse.com as my server, sending pictures, saving user data etc. With all of this data the app...

Garbage Collector doesn't immediately collect finished thread [duplicate]

java,multithreading,memory-management,garbage-collection
This question already has an answer here: Why does java wait so long to run the garbage collector? 6 answers In short: I have a thread which is finished running, but not garbage collected. In long: See following example code: public void saveSomething() { Thread thread = new Thread(new...

Strange error while adding a feature to my little game (0xC0000005)

c,memory-management,memory-leaks,heap-memory
Hello everyone, I decided some time ago to write my own version of Minesweepers as some practice and I did it. The game ran perfectly, but after deciding to add a "Choose difficulty" option the window freezes and I get an error message, saying that the program does not respond....

Allocate 2D Array in C (not array of pointers) in Heap

c,arrays,pointers,memory-management,allocation
I have a simple question, but the answer seems to be very difficult to find: How do I create a true 2D array in C (not C++), dynamically sized (size not known at compile time), not an array of pointers, on the heap, so that I can put that allocation...

Is there a difference between new List() and new List(0)

c#,.net,list,memory-management
Is there a difference between new List<T>() and new List<T>(0) ? May be this is a micro-optimization, but the idea is to understund the difference in term of memory allocation....

Java how to limit number of threads acting on method

java,multithreading,memory-management
I have java method in my web application doing heavy file operation. The thing is, if more than 5 threads come simultaneously (which will come in testing phase) it breaks down. I mean it cannot handle heavy traffic. That's why I want to handle maximum 5 requests at a time...

xCode 6.3.2 Crash [UIViewController .cxx_destruct]

objective-c,xcode,core-data,memory-management
I have converted an application written in Objective-C, previously using SQL, now changed to CoreData. Issue I identify so far is when I changed NSObject to NSManagedObject in only one of class I am getting this stupid crash in ViewController after View is completely dismissed: [self dismissViewControllerAnimated:YES completion:nil]; Control stopped...

When calling append on stringbuilder, are we adding strings to the heap?

c#,.net,memory-management,stringbuilder
I am wondering about the benefits of using stringbuilder when it comes to memory usage in C#. If you have the following scenario: var strBuilder = new StringBuilder(); for(int i=0;i<1000;i++) { strBuilder.Append(i); /// is this not calling i.ToString(); ??? strBuilder.Append(','); /// this i character comma strBuilder.Append(" and "); /// this...

Weak and strong property implementation

objective-c,memory-management
I want to better understand strong and weak pointers implementation, and i figure out assumptions, about how their setter methods would look like (correct me if i wrong please). First, strong pointer, look like: - (void)setObj:(NSObject*)Obj // Setting Strong Obj { //First, check either we trying to set old value...

Explanation of why allocating a large array results in segmentation fault in C [duplicate]

c,arrays,memory-management
This question already has an answer here: Segmentation fault on large array sizes 5 answers Memory allocation for global and local variables 3 answers I'm not too experienced in C, but I've been recently writing some program in the language to speed it up a little bit (it was...

Modern C++ idiom for allocating / deallocating an I/O buffer

c++,memory-management,io
For I/O work, I need to read N bytes into a buffer. N is known at run time (not compile time). The buffer size will never change. The buffer is passed to other routines to compress, encrypt, etc: it's just a sequence of bytes, nothing higher than that. In C,...

Multipart form uploads + memory leaks in golang?

memory-management,memory-leaks,go
The following server code: package main import ( "fmt" "net/http" ) func handler(w http.ResponseWriter, r *http.Request) { file, _, err := r.FormFile("file") if err != nil { fmt.Fprintln(w, err) return } defer file.Close() return } func main() { http.ListenAndServe(":8081", http.HandlerFunc(handler)) } being run and then calling it with: curl -i...

malloc() - Does it use brk() or mmap()

c,memory-management,malloc,mmap,sbrk
c code: // program break mechanism // TLPI exercise 7-1 #include <stdio.h> #include <stdlib.h> void program_break_test() { printf("%10p\n", sbrk(0)); char *bl = malloc(1024 * 1024); printf("%x\n", sbrk(0)); free(bl); printf("%x\n", sbrk(0)); } int main(int argc, char **argv) { program_break_test(); return 0; } When compiling following code: printf("%10p\n", sbrk(0)); I get warning...

Memory error in set resize

c,memory-management
Here's a structure of set that I've written: struct state_set { struct state ***state_array; size_t *slot_sizes; size_t *slot_memory; }; Here's an initializer: struct state_set *state_set_init() { struct state_set *new_set = malloc(sizeof(struct state_set)); new_set->state_array = malloc(ARRAY_SIZE * sizeof(struct state**)); new_set->slot_sizes = malloc(ARRAY_SIZE * sizeof(size_t)); new_set->slot_memory = malloc(ARRAY_SIZE * sizeof(size_t)); for (int...

Does free() set errno?

c,linux,memory-management
If buf is a malloc() allocated char buffer, does free(buf) set/reset errno? Let's say I want to write the buffer to a file, and then free it, as I don't need it any more. Let's say the error policy for the code is to return -1 on an error. Is...

Proper memory cleanup with c_str() and const char *

c++,memory-management,stdstring,const-char
I have a function that takes a (char* const*). The data I am provided is in a std::string. So I'm doing this: void blahblah(std::string str) { const char * cc = str.c_str(); ConstCharFunction(&cc); } This works well. My question is do I need to clean-up the memory used by the...

Where C++ calls destructors?

c++,class,memory-management,destructor
Assuming Member and MyList are two user defined classes. In the following code: void fillList(MyList &list1) { Member m1("aaa"); Member m2("bbb"); list1.insert(m1); list1.insert(m2); } void func1() { MyList lst; fillList(lst); lst.printAll(); } int main() { func1(); return 0; } At which point does C++ call destructor of each m1, m2...

Retain cycle in Swift when Object A has Object B as a property and Object B has an array property that contains Object A?

ios,swift,memory-management,memory-leaks,retain-cycle
Confused about a situation that might be a retain cycle? I understand that if class Object-A { var b: Object-B } and class Object-B { var a: Object-A ] then above is horrible design because if you do var a = Object-A() var b = Object-B() a.b = b b.a...

Ideal memory usage amounts for iOS apps

ios,iphone,ipad,memory-management
What ranges could be considered Low, Medium, and High in memory usage? As my app becomes more complex, I notice this number getting higher. I've been trying to use this number as an indicator to how efficiently I'm coding but I've realized I have no bar to compare it with....

Sharing std::string across shared memory

string,c++11,memory-management
I wish to share a std::string across processes using shared memory. However, I'm concerned about where the string object is allocated, on the stack, or heap, as this will affect the share. Referring to this, MSDN Forum ...it says : please note that in new STL (Visual Studio 2003 and...

How can I ensure an emxArray is correctly allocated in generated C code?

matlab,memory-management,matlab-coder
I have the following .m file (named testmemoryallocation.m), targeted for code generation in Matlab Coder. This is just a test file demonstrating the concept, of course. function output = testmemoryallocation(dim) %#codegen %TESTMEMORYALLOCATION Tests allocation of large 3D arrays output = coder.nullcopy(zeros([dim, dim, dim])); output(:) = 5; end I build this...

Understanding Stack, Heap and Memory Management

c++,pointers,memory-management,stack,heap
int *ip = new int[10]; for (int i = 0; i<10; i++) *(ip+i) = i; myfun(ip); // assume that myfun takes an argument of // type int* and returns no result delete [] ip; The above code is a small segment of a test function that I am trying to...

Memory address in linked list C++

c++,memory-management,linked-list
I have created an extremely simple linked list example in C++ to practice some interview questions. I am having one strange issue that I can't really seem to understand: while( cur ) { cout << "Index: " << indx << endl << "Current Add:\t" << &cur << endl << "Value:\t\t"...

memory content not erased after deleting my pointer (on a simple example) [duplicate]

c++,pointers,memory-management
This question already has an answer here: Can a local variable's memory be accessed outside its scope? 16 answers Here is a simple of example of a question I have: I create a pointer of integer (value 5), I print the pointer (hence the address) of the memory case...

Memory analysis in Android: dominator_tree does not show all the instances of some objects

java,android,eclipse,memory-management,eclipse-memory-analyzer
I'm using Eclipse Memory Analyzer, for testing the behavior of MainActivity in my Android app. I've rotated my device exactly 10 times, so I have created 11 instances of MainActivity class. Looking at the Histogram tab in Eclipse Memory Analyzer, I obtain this The entire list objects (right click ->...

Is BitSet worth using?

java,memory-management,bitset
I made a Java object that has a lot of Boolean fields. I was considering using BitSet when I started questioning its usefulness. Of course, one would use it for memory reasons, since a boolean is 8 bits alone, 4 in an array. With BitSet, each value is stored as...

Are memory addresses in assembly language statically allocated at once?

c,assembly,memory-management,static,allocation
I would like to write a C-program that allocates 20,000 memory lines with each line containing 8 bytes and are labeled in the range 2500 to 24999.. The program actually simulates a simple assembly language IDE. All the 20,000 memory lines may or may not be used at once. Suggest...

Why I cannot use “fgets” to read a string to an element of my Struct?

c,pointers,memory-management,struct,fgets
I'm trying to create a program almost like "bank" using struct, but when the program should have read the string (variable "nome" that is name in portuguese) it totally ignore the "fgets" that I used. This is the part that I was talking about : printf("\nNome: \n"); fgets(vet[cont+1].nome, sizeof(vet[cont+1].nome), stdin);...

At what size should I malloc structs?

c,memory-management,struct,malloc
Most examples using structs in C use malloc to assign the required size block of memory to a pointer to that struct. However, variables with basic types (int, char etc.) are allocated to the stack and it is assumed that enough memory will be available. I understand the idea behind...

Using mmap and madvise for huge pages

c,linux,memory-management,mmap,huge-pages
I want to allocate memory on the hugepages being used by a Linux machine. I see that there are two ways to do this, using mmap and madvise. That is, using the MAP_HUGETLB flag with the mmap call - base_ptr_ = mmap(NULL, memory_size_, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS |...

Convert IntPtr to char** in C#

c#,memory-management,types,type-conversion,dllimport
I'd like to interpret the output of the following unmanaged function: afc_error_t afc_get_device_info (afc_client_t client, char ***device_information) I import the dll with the code: [DllImport("libimobiledevice.dll", CallingConvention = CallingConvention.Cdecl)] internal static extern short afc_get_device_info(IntPtr client, out IntPtr info); As long as I only needed to convert response to string Marshal.PtrToStringAnsi was...

Temporary variable destroyed with overloaded + and += operator

c++,memory-management,operator-overloading
I am getting a segfault because I believe my temporary variable is being destroyed (freeing allocated memory) before the operators are done using it. This is the code in my main: int main(int argc, char *argv[]) { Bcd b1 = Bcd(100), b2 = Bcd(20), b3 = Bcd(50); b3 += b1...

Retain cycle with parent-child construction

ios,objective-c,memory-management,memory-leaks,retaincount
Its very common question everybody familiar with, but I'm still not understand it fully. If Object A owns (have a strong property of) Object B, and Object B have a strong property of object A, there is retain cycle, and no object can be released and there is a memory...

c - unsetenv() implementation, is it necessary to free memory?

c,memory-management,setenv
As TLPI exercise 6-3 required, I made an implementation of setenv() and unsetenv() using putenv(), getenv() and via modifing environ variable directly. Code: // setenv() / unsetenv() impl // TLPI exercise 6-3 #include <stdio.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <errno.h> #define ENV_SEP '=' extern char **environ; // setenv()...

How to copy bytes from memory using pattern (YUYV packed to YUV420 planar)

c++,memory-management,video-processing,micro-optimization,pixelformat
Let's start with this: I have a block of memory of 16 bytes and I need to copy only even bytes to a 8 bytes block of memory. My current algorithm is doing something like this: unsigned int source_size = 16, destination_size = 8, i; unsigned char * source =...

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; } ...

Managing memory of Vector3's created to move gameObject

c#,memory-management,memory-leaks,unity3d
I'm coming from a C++ background and am new to both C# as well as Unity5 Game Engine. I'm currently working through some of the tutorial projects (Space Shooter) and have a doubt about memory management. Consider this code to apply user input to move the player gameObject: void FixedUpdate...

Get VU of VSXu artiste with C++

c++,memory-management,dll,base-address,cheat-engine
this is my code so far: #include "iostream" #include "Windows.h" #include "stdio.h" using namespace std; int main() { HWND hWnd = FindWindow(NULL,TEXT("Vovoid VSXu Artiste 0.4.0 [Windows 64-bit]")); if (hWnd == 0) { cerr << "Cannot find window "<< endl; } else { DWORD pId; GetWindowThreadProcessId(hWnd, &pId); cout << "Found Window...

What is a “non-weak zeroing reference”

objective-c,cocoa,memory-management,nsnotificationcenter,osx-elcapitan
In the OS X v10.11 beta release notes, I find the following: NSNotificationCenter and NSDistributedNotificationCenter no longer send notifications to registered observers that may be deallocated. If the observer is able to be stored as a zeroing-weak reference the underlying storage stores the observer as a zeroing weak reference. Alternatively,...

Allocating memory for pointers inside structures in functions

c,pointers,memory-management,struct
Let's say I declare a structure as it follows: typedef struct { int *numbers; int size; // Size of numbers once treated as array } sstruct; And I create in main() a pointer to structure (in order to later pass it by reference) using sstruct *example;. Then I have a...

Deleting a dynamically allocated 2D array [duplicate]

c++,memory-management,delete-operator
This question already has an answer here: delete vs delete[] [duplicate] 4 answers So I'm used to memory management in C where free(pointer) will free up all space pointed to by pointer. Now I'm confusing myself when attempting to do something simple in C++. If I have a 2D...

Why should I dimension my variables in VBA really?

vba,memory-management
They used to say it was about memory management. However, having a look at things I find that failure to dimension a variable will default it to a variant data type which allocates 22 bytes of memory. Let's consider just a single megabyte of memory. 1,000,000 bytes. This means I...

Using Picasso to solve OutOfMemoryError

android,memory-management,out-of-memory,picasso
I have seen many answers on this issue which has not worked so far for me, the best option I got was using a Picasso to solve this, I have imported the .jar but am getting an error on the code I was told to use, I get an error...

Should I outsource allocation algorithm? (RAII)

c++,memory-management,raii
Right now my class has a constructor, copy constructor and copy assignment operator which all do the same thing at first (allocating memory). The destructor is deallocating the memory. class Register { public: Register() { _trampoline_address = reinterpret_cast<BYTE*>(VirtualAlloc(nullptr, _trampoline_size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE)); if (_trampoline_address == nullptr) { throw my_exception("Could...

Is the memory assigned to a strong property released as soon as the property is set to nil?

objective-c,memory-management,automatic-ref-counting
I would like to know how to release a strong property/iVar. I would like to clarify why I intend to do this. I own an object via any one of these declaration: @interface MyClass : NSObject @property (readwrite, nonatomic) MyObject *hugeObject; @end OR @interface MyClass : NSObject { MyObject *hugeObject;...

C# apps using ram and cannot be cleared

c#,memory-management
Okay, i had create an apps and the apps are eating ram too much. The Problem: At the clearing process, i dispose the object but the ram usage isn't going down I don't have any idea, where is the mistake. How the program works Started user press space -> screen...

Valgrind says about “Invalid write” in fclose()

c++,memory-management,valgrind
I created a stream using fmemopen(). I am closing it with fclose() and freeing the buffer after reading. Valgrind reports about problem at fclose() line: ==9323== Invalid write of size 8 ==9323== at 0x52CAE52: _IO_mem_finish (memstream.c:139) ==9323== by 0x52C6A3E: [email protected]@GLIBC_2.2.5 (iofclose.c:63) ==9323== by 0x400CB6: main (main.cpp:80) ==9323== Address 0xffefffa80 is...

Objective-C memory leak when returning NSString

ios,objective-c,iphone,memory-management,memory-leaks
I want to be sure that my code is not leaking, since this small snippet is called thousand times in my app. I run the app through Instruments and the initWithBytes seems to be problematic. Is anything wrong in this code? First [reader readString] is called. case FirstCase: { NSString...

Fast memory allocation for real time data acquisition

c++,memory-management
I have a range of sensors connected to a PC that measure various physical parameters, like force, rotational speed and temperature. These sensors continuously produce samples at some sample rate. A sample consists of a timestamp and the measured dimension itself; the sample rates are in magnitudes of single-digit kilohertz...

Android - effective performance and memory management

java,android,memory-management,memory-leaks
I have a class MyClass which contains a large buffer, about 12Mb. While my application is working, the instance of this class is constantly (50 times per second) updated. What would be the most memory and performance wise way : to create a new object for each update and let...

HTTPNetStreamInfo::_readStreamClientCallBack(__CFReadStream*, unsigned long) increases memory allocation

ios,memory,memory-management,xamarin,httpclient
I am trying to download large video file with httpClient post method. I am working Xamarin.iOS, but it seems to be issue of iOS (NSURLConnection/session) as the Xamarin codes convert it into native one. My device is having IOS8.1. A memory is kept increasing when I try to download that...

Most efficient way to clone a list into an existing list, minimizing memory reallocation?

c#,performance,list,memory-management,clone
I have a need to clone an existing list into another, existing list. As the environment demands very high performance, I need to eliminate unnecessary memory reallocation. The most efficient algorithm I can think of is the following, which will increase the capacity of the destination list to match the...

Local const in recursion call

python,memory-management,recursion
Well... Code first. def magic(node): spells_dict = {"AR_OP":ar_op_magic, "PRE_OP":pre_op_magic} if node: if node.text in spells_dict: return spells_dict[node.text](node) else: return magic(node.l) + magic(node.r) else: return "" During recursion calls there will be created a lot of spells_dict copies. I know that I can make that dict global, but I don't want,...

URLClassLoader Memory Leak Java

java,memory-management,memory-leaks,urlclassloader
I have been going through a lot of URLClassLoader Memory leak solutions on the internet, but I haven't found any fully working code and precise solution. The closest to a solution I found was this Any fully functional code or link to it, which uses WeakHashMap() or any other definite...

function to get 2d-arrays from stack and heap

c,arrays,memory,memory-management,malloc
Consider a simple struct, Foo, which contains a pointer to some other strucrt, Baz. and a two-dimensional array, (stack-allocated): Foo arr[ARR_SIZE][ARR_SIZE]; Next, consider a function which mallocs (in the heap, obviously) a memory for a new 2d-array of Foos. A code snippet: Foo** arr_copy = malloc(sizeof(Foo*) * ARR_SIZE); for (int...

munmap_chunck(): invalid pointer in c

c,pointers,memory-management,global-variables
I have a program that I've written to do some data analysis, and this data is stored in a global structure called P. I allocate the memory for this structure in one function and then, since I need it for the entire program, don't call free until the very end...

Operator Overloading without memory copies

c++,memory-management,operator-overloading
Imagine we have the type A and we want to do the following operation: A operator -(const A& a, const A& b) { A c; //... return c; } When we call this operator, we do something like this: A c; c = a - b; Basically we are allocating...

C++ vector only save the last push_back value

c++,memory-management,vector,push-back
I am a newbie, I have a problem which trouble me a lot. Please help me out. I am trying to save char array values in a vector. The size of the vector is the same as the number I push_back. However, all the values in the vector is the...

Unable to increase PHP Memory Limit

php,apache,memory,memory-management,out-of-memory
I am running into an issue with a project I am working with on my localhost, where I am unable to increase the PHP memory_limit setting. I've tried increasing it directly in the php.ini config: memory_limit = 1024M I've tried increasing it in the projects .htaccess file: php_value memory_limit 1024M...

calloc created array is not acting as expected

c++,pointers,memory-management,calloc
I was bored and wanted to make a program to crash my computer :P. I would have it uselessly and redundantly allocate memory until the crash. The code I created so far is here: #include <cstdlib> #include <cstdio> int main(int argc, const char *argv) { int n = 0; while...

Efficiently transferring elements between arrays

javascript,arrays,optimization,memory-management,data-structures
I have several JavaScript arrays, each containing a list of pointers to objects. When an object meets a certain condition, its pointer must be removed from its current containing array and placed into a different array. My current (naive) solution is to splice out the exiting array elements and concatenate...

Large memory pages and fragmentation

linux,memory-management,shared-memory,ppc
I am using Linux + PPC64 where the memory page size is 64KiB. If I were to make two separate 32KiB allocations from within the same process, would that take up a single page in memory or two? Thanks!

S_realloc: How to increase the length of a *numeric* vector? (first argument not char*)

c,r,memory-management
In C code called from R via .Call, I pass a double *vector to a function for filling vector with numbers. I don't know how large vector will be in the end, so I keep track of its number of elements vector_size and use S_realloc(vector, vector_size+64, vector_size, vector_size * sizeof(double))...

Necessary to delete dynamic struct contents, and then the struct itself?

c++,memory-management
#include <cstring> using namespace std; struct Product { char * name; float price; }; int main() { Product * bread = new Product; bread->name = new char[6]; bread->name = "bread"; delete[] bread->name; //!!!THE ERROR OCCURS ON THIS LINE!!! delete bread; } Gives me the following error: *** Error in `./out':...

physical memory userspace/kernel split on Linux x86-64

memory,memory-management,linux-kernel,kvm
Is there an explict split between userspace and kernel in physical memory on Linux x86-64? That is, given a physical address, can I tell whether this address is from userspace or not? As far as I know, in virtual address space, the kernel will use the upper half and the...

How to get current memory page size in C#

c#,.net,memory-management
I need to determine the memory page size in C# without using "Kernel32.dll" SYSTEM_INFO si; GetSystemInfo(&si); This is very important because the code should be cross platform and we should not have platform specific code. Is there any .NET class who provides that data? Thanks, Valentin...

Bitshifting on little-endian and big-endian [duplicate]

c++,memory,memory-management,binary
This question already has an answer here: Bitwise operators and “endianness” 5 answers Will this: ((0x10203040 >> 24) & 0xFF) == 0x10 always be TRUE on both little-endian and big-endian machines?...

Fortran memory allocation does not give an error, but the program is killed by OS at initialization

memory-management,fortran
Given the minimal working example provided below, do you know why the memory allocation error does not occur at memory allocation step? As I checked, when I use valgrind to run the code, or add parameter source=0.0 to memory allocation statement, then I have, as expected, the memory allocation error....

nodejs decrease v8 garbage collector memory usage

node.js,memory-management,garbage-collection,v8
I'm debugging a nodejs application with util module and while heapUsed value stays around 30-100MB, heapTotal value grows up to 1.4GB. Here is a question about similar behaviour I've read that this is the way how v8 garbage collector behaves, but the question is how to decrease the amount of...

When do autorelease pools drain?

ios,objective-c,memory-management
I study manual memory management and I wonder when autorelease pools drain. There is 3 situations, that I found: 1 - in the main.m, start from application running and drains on end, therefore releasing all of objects in memory. 2 - when you explicitly create an autorelease pool manually and...

Using a data pointer with CUDA (and integrated memory)

c++,memory-management,cuda
I am using a board with integrated gpu and cpu memory. I am also using an external matrix library (Blitz++). I would like to be able to grab the pointer to my data from the matrix object and pass it into a cuda kernel. After doing some digging, it sounds...

Why this memory management trick works?

c#,memory-management,unity3d
Refers to this Unity documentation and go to section Large heap with slow but infrequent garbage collection var tmp = new System.Object[1024]; // make allocations in smaller blocks to avoid them to be treated in a special way, which is designed for large blocks for (int i = 0; i...

Host testing C program with hard coded memory addresses

c,linux,unit-testing,memory-management,functional-testing
We will write functional/unit tests for C code. This C program will be run as embedded software. However we need to run tests on a Linux environment. The problem is that parts of the code under test looks like this: my_addresses.h: #define MY_BASE_ADDRESS (0x00600000) #define MY_OFFSET_ADDRESS (0x108) my_code.c #include "my_addresses.h"...

How are Strings created and stored in Java?

java,string,memory-management,immutability,hashcode
To understand how String objects are created and stored, I tried the following program and I see output against which I have query. Can somebody please help? package corejava.immutable; public class StringTester { public static void main(String[] args) { // TODO Auto-generated method stub String s1 = "Omkar Patkar"; String...

When do I need to free a Data Module created by the Application?

delphi,memory-management,datamodule
i have the code as follows: begin Application.Initialize; Application.Title := 'Controle Bancário'; Application.CreateForm(T_DMEstagio, _DMEstagio); Application.CreateForm(T_frmLogin, _frmLogin); if (_frmLogin.ShowModal = 1) then begin FreeAndNil(_frmLogin); Application.CreateForm(T_frmPrincipal, _frmPrincipal); Application.Run; end; _DMEstagio.Free; end. If I DONT explicitly free the DM as I did in the code, I get an Access Violation Exception, but in...

Free memory of byte[]

c#,memory-management
I'm currently struggling with memory usage in c#. The tool I'm currently working on is able to up- and download files. For that it is using byte arrays as buffers for the file contents. After an up- or download operation I can dispose the WebResponse and the Stream(+Reader/Writer) objects, however...

uninitialized data segment of program memory

memory-management,heap-memory
In Uninitialized Data Segment, the kernel initialize the uninitialized variable to 0. But if we directly use an uninitialized variable (for eg. int sum; and not int sum=0; ) and use it in program like sum=sum+n(n be any number), sum will take any garbage value. So why the sum will...

c++ dynamically declared array fails to work

c++,memory-management,new-operator,theory,heap-memory
I am trying to read the file's data into a dynamically declared array, using double *data = new double[14141414]() declaration. Note, it is rather a large file; hence large size of an array. The problem is I can not put all the data into an array as somewhere around index=14000000...

Memory Management (Allocating Pages/Frames to Logical Addresses)

memory,memory-management,operating-system,paging,virtual-memory
I am new to Operating Systems and I was following this handbook which I am reading to get a better grasp on how computers really work. However having stumbled upon Memory Management I found it somewhat confusing when allocating Frames to Pages using Page tables. Say Page/Frame size is 4K...

Cannot free fileName char * after fclose

c,memory-management,malloc,free,realloc
I am trying to free my file name (char * pointer) but got an error : Heap corruption detected: after normal block (#65) at 0x.... The code: static FILE *initializeIndexFile(char *database, char **indexFileName) { FILE *file1_p; *indexFileName = NULL; int len = strlen(database); *indexFileName = (char *)malloc(len *sizeof(char) + 1);...

Function in C extension randomly stops python program execution

python,c,memory-management,random,python-c-extension
I am relatively new to C extensions for python. I wrote an extension that shows a behavior that seems weird to me. When I run a python script using this extension the script stops randomly after the routine in the extensions has been successfully executed. That is, I have a...

Disadvantages of calling realloc in a loop

c,memory-management,out-of-memory,realloc
I'm trying to implement some math algorithms in C on Windows 7, and I need to repeatedly increase size of my array. Sometimes it fails because realloc can't allocate memory. But if I allocate a lot of memory at once in the beginning it works fine. Is it a problem...

Core Data One-To-Many Relationship Memory Usage

ios,core-data,memory-management,one-to-many
I am using core data where I have object A which has a one-to-many relationship with object B. In practice there could be 1000s of Bs related to one A. My concern is that when I define the inverse of the one-to-many relationship, object A will have a NSSet containing...

When a view controller is dismissed, should it empty the memory?

ios,objective-c,memory-management,uiviewcontroller,automatic-ref-counting
I'd like to learn about memory management in Objective-C which I find not that easy because I'm fairly new at Objective-C and ARC and I'm mostly used to script languages for which I don't have to deal that much (or not at all) with memory management. The app I'm working...

Is free() zeroing out memory?

c,gcc,memory-management,clang,free
Until today I lived in belief that calling free() on memory space releases it for further allocation without any other modifications. Especially, considering this SO question that clearly states that free() DOESN'T zero out memory. Yet, let's consider this piece of code (test.c): #include<stdlib.h> #include<stdio.h> int main() { int* pointer;...

How to have my program stops if its memory consumption exceeds a limit ?

c++,linux,memory-management
I develop a C++ framework that is used to run user code in a well defined environment (Linux boxes under our supervision). I would like to prevent badly written modules to start eating up all memory of a machine. As I develop the framework could I simply force the program...

Invalid free() / delete / delete[] / realloc(), 4 bytes inside a block of size 16 alloc'd [closed]

c++,memory-management,vector,valgrind
I've written a program using C++. It runs fine until the end, where it vomits: * Error in `./xwd': free(): invalid pointer: 0x00000000017fd774 * My first thought was that I was doing something wrong in the destructor, but as the relevant class has no destructor as it doesn't use "new",...

QEvent ownership

c++,qt,memory-management
I want to send both predefined and custom QEvent to a Qt application. Is the event required be allocated on the heap or can I just pass the pointer to a object on the stack? QKeyEvent stackevent(QEvent::KeyPress); QKeyEvent* heapevent = new QKeyEvent(QEvent::KeyPress); QEvent * event; event = &stackevent; //valid ??...

How to free memory in C# that is allocated in C++

c#,c++,memory-management,dll,memory-leaks
I have a C++ dll which is reading video frames from a camera. These frames get allocated in the DLL returned via pointer to the caller (a C# program). When C# is done with a particular frame of video, it needs to clean it up. The DLL interface and memory...

Simple explanation about loading files into memory

vb.net,visual-studio-2010,memory-management
What does it mean to "load into memory"? I watched some videos online where they were talking about reducing processing reports times, and they constantly say "you don't want to load a huge file into memory, instead read line by line." Can I have an example of what loading a...

C memory allocation and deallocation

c,memory-management
I have written the following C function that returns a double pointer after necessary memory allocation. // integer double pointer to 2d array void** idp_to_2d ( int rows , int cols ) { int i ; void **est = malloc ( rows * sizeof ( int* ) ) ; for...

libXML: check if node is already unlinked and freed

memory-management,xpath,libxml2,vala
I am parsing a html document with libxml2 and remove some elements based on xpath querys. For example I want to remove all elements that contain "display: none" with: stripNode(doc, "//*[contains(@style,'display:none')]"); ... public static void stripNode(Html.Doc* doc, string xpath) { Xml.XPath.Context cntx = new Xml.XPath.Context(doc); Xml.XPath.Object* res = cntx.eval_expression(xpath); if(res...

DataTable does not release memory

c#,memory,memory-management,datatable
I have a data loading process that load a big amount of data into DataTable then do some data process, but every time when the job finished the DataLoader.exe(32bit, has a 1.5G memory limit) does not release all the memory being used. I tried 3 ways to release memory: DataTable.Clear()...

Memory management in Contiki-OS

memory-management,heap-memory,contiki
I am trying to create a port for Contiki-os to LPC1347, and i have a question as to how exactly is memory handled in Contiki. Protothreads are stack-less and no "real threads" are used so everything is basically on the same stack, so it is basically static memory allocation. I...

Getting many memory errors when try to run it for few days in my web crawler [on hold]

java,memory,memory-management,out-of-memory
I am developing a web crawler application. When i run the program i am getting these error messages below: i've got these errors after running the program for more that 3 hours. I tried to allocate memory by changing eclipse.ini setting to 2048 MB of ram as it was answered...

How to translate these logical addresses into physical addresses?

memory-management,operating-system
Given that: Logical addresss space=64 bits Physical address space=32 bits Page size=4K How will the logical addresses 20, 4100 and 8300 be mapped to physical address for the following page table? ...

emptying an std::queue through a function that returns the front() and pops()

c++,memory-management,destructor
I'm writing a template class that is supposed to provide a queue protected against concurrent access, basically to be able to write classes that can treat a list of items with a variable number of concurrent worker threads. The template class has a method: bool getFront(T &value) { CritSectEx::Scope scope(listLock);...

How is garbage collection triggered in JavaScript?

javascript,memory-management,garbage-collection
Consider JavaScript code below. I am creating array of let's say 4 elements and then immediately delete reference to it. When will garbage collection happen? I know it is specific to language implementation, but we have not that many JavaScript engines. Edit: it is the simplest possible case, but it...

free() and mxFree() in MATLAB - freeing memory twice

matlab,memory-management,free,mex
Good day, I have the following code which has given me problems for a day already. I have debugged it, and it works fine until trying to free the memory. The free() function should be called at the end of the execution automatically, so I commented the mxFree() code out,...