c++,memory,memory-management,malloc,new-operatorRelated issues-Collection of common programming errors
UserABC
c++ google-chrome-extension google-nativeclient
I am trying to create an Extension for Google Chrome ,in which I want to process some images. The extension was previously created using NPAPI ,but that being phased out need to switch to another alternative, Native Messaging looked like the best suited for this job. The native host is written in C++ and it reads from stdin a formated message sent from extension(some like {action:”name_of_action”,buffer:”x0x0″,length:”4″} ),parse it ,extract the buffer and do some processing with the image,after
Mihai
java c++ jvm jni
I am developing a Java application that calls a native dll library. My code for the c++ method that I call:JNIEXPORT jobjectArray JNICALL Java_Surf_TopSurfWrapp_computeSurfExtractDescriptor__LSurf_TopSurfVisualword_2Ljava_lang_String_2(JNIEnv *env, jclass c, jobject vw, jstring imagePath) { c = env->GetObjectClass(vw); printf(“start\n”); jobjectArray ret = (jobjectArray) env->NewObjectArray(100, c, vw);for (int i = 0; i < 100; i++) {jmethodID visualWordConstructor = env->GetMethodID(
Pavel
android c++ android-ndk jni
I use regular std::map to map jobject’s to c++ objects. The problem with this approach is that it may fail for other types of references, e.g. global references are actually different pointer than regular local references even if they reference the same object. The correct way to compare if two references reference the same object is:env->IsSameObject(jobj1, jobj2);So, my question is: what’s the correct way to map jobject’s to c++ objects? The obvious reply to wrap jobject into some c++ class
Nico
c++ windows windows-runtime directx idl
This is a problem I encounter quite often. I have some object (in this case a trackball) that I want both the class that receives TouchStart, TouchMove, and TouchEnd events to have a handle on (so it may delegate it quickly), like so:// Direct3DBackground.cpp // Event Handlers void Direct3DBackground::OnPointerPressed(DrawingSurfaceManipulationHost^ sender, PointerEventArgs^ args) {m_trackball.TouchStart(args); }void Direct3DBackground::OnPointerMoved(DrawingSurfaceManipulationHost^ sender, Poin
Santhosh
c# c++ datetime
I have a C++ client talking to a C# server and I have custom serialization for user defined types.Now I need to pass a date and time structure from C++ to C#. Googling led to the following approach:Fill up the date/time in SYSTEMTIME structure (This is not the current system time. But rather it will be filled up by the program based on certain conditions) Convert SYSTEMTIME to FILETIME Convert FILETIME to __int64 (this gives a 64 bit value representing the number of 100 nanoseconds interval fro
Xcelled194
c# c++ winapi dll
This a question arising from this thread: Native C++ use C# dll via proxy C++ managed dllIn a nutshell, I’m loading (my) C# extension into a native process via a DLL. The extension needs to show a form so that the user can control it. I’m using standard .NET forms, no 3rd party librarys or anything, and my form is not showing up. Worse yet, it hangs the target process. It’s not using any CPU, so I get the feeling its waiting for some function to return, but never does.Also of interest is that th
Bret Kuhns
c++ visual-studio-2010 mfc c++-cli
I’m just experimenting with mixing a native C++ (that uses MFC) static lib and a C++/CLI WinForms application. When I try to include my NativeClass.h, compiling the C++/CLI app fails because it doesn’t understand AFX_EXT_CLASS used to export the class for the lib.Just to get it working, I was able to build the native lib, then remove the AFX_EXT_CLASS from the header, then build the C++/CLI linked to the native lib. The C++/CLI app will run, the dialog comes up and outputs some dummy value from
user1966723
c++ opencv android-ndk jni undefined-reference
I tried to build a OpenCV JNI Example (native-activity). I deleted most of the java stuff ( i only want to try some OpenCV JNI). I added the paths in c/c++ general -> Paths and Symbol -> GNU C++ (sorry cant post screenshot)${NDKROOT}/sources/cxx-stl/gnu-libstdc++/4.6/include ${NDKROOT}/sources/cxx-stl/gnu-libstdc++/4.6/libs/armeabi-v7a/include ${NDKROOT}/sources/android/native_app_glue ${NDKROOT}/platforms/android-19/arch-arm/usr/include C:\Android\Development\OpenCV-2.4.7-android-sdk\sdk\native
sfireman
c++ clr cli mixed
I’ve created C++ DLL project, this dll contains mostly native c++ code, but it have 1 mixed class written in C++ and using some .NET types. This class is declared in header file and have implementation in .cppI can use it from all *.cpp files, but when i try to declare reference to C++/CLI class in some c++ header file i got tons of errors about project doesnt support CLR(CLR support in project settings as /clr is set up), it looks like header files doesnt support links to managed classes.This w
adrian8400
c++ debugging memory winapi
I’m working with a single-threaded native c++ application. There is a very hard to reproduce bug that I cannot reproduce locally. I enabled full page heap and debug information in the release executable, and obtained dumps from a client (which has to use the application many days to get the bug).What the client reports: the application hangs and never recovers. It has to be killed from the task manager. What I see from the dumps: the application is stuck in an infinite loop.The loop is from wal
adrian8400
c++ debugging memory winapi
I’m working with a single-threaded native c++ application. There is a very hard to reproduce bug that I cannot reproduce locally. I enabled full page heap and debug information in the release executable, and obtained dumps from a client (which has to use the application many days to get the bug).What the client reports: the application hangs and never recovers. It has to be killed from the task manager. What I see from the dumps: the application is stuck in an infinite loop.The loop is from wal
Robin van Dijke
ios core-data memory
I’m now stuck for about two weeks with a nasty Core Data problem. I read lots of blogpost, articles and SO questions/answers but I’m still not able to solve my problem.I ran lots of tests and was able to reduce the larger problem to a smaller one. It’s going to be a large explanation so keep with me!Problem – datamodelI have to got following datamodel:Object A has one-to-many relation with object B which has another one-to-many relation with object C. Because of Core Data recommendations I have
jwiklund
java memory jhat
How do you find a memory leak in Java (using for example JHat)? I have tried to load the heap dump up in JHat to take a basic look. However I do not understand how I am supposed to be able to find the root reference (ref) or whatever it is called. Basically I can tell that there are several hundred meg of hash table entries ([java.util.HashMap$Entry or something like that), but maps are used all over the place… Is there some way to search for large maps, or perhaps finding general roots of lar
GHH
python memory dictionary bytecode
I need to import a very large dictionary into python and I’m running into some unexpected memory bottlenecks. The dictionary has the form,d = {(1,2,3):(1,2,3,4), (2,5,6)=(4,2,3,4,5,6), … }So each key is a 3-tuple and each value is a relatively small tuple of arbitrary size (probably never more than 30 elements). What makes the dictionary large is the number of keys. A smaller example of what I’m working with has roughly 247257 keys. I generate this dictionary through a simulation so I can wri
thegrinner
python memory
I don’t understand why my script is failing with an out of memory error after it runs about 200 tiles. I have looked at the script and am not sure what it’s writing to memory that is so large that it fails…The scriptimport os, glob, arcpy, csv, sys, shutil, datetime top = r’L:\Raster_Data’ # Source directory for all files to check and process #top = os.getcwd() RootOutput = r’H:\Raster’ # Directory to copy/move files to FileList = csv.reader(open(r’P:\2013\508_Data_Split_MSC\Working\LiDAR_Tile
bk1e
c++ string memory vector
I’m using C++ and it’s STL. I have a large (100MB+) text file. This file just has a lot of “words” (strings separated by whitespace) like:sdfi sidf ifids sidf assd fdfd fdfd ddd dddI need to put each of these “words” in a vector: vector<string> allWordsInFile;So for each word that I read from the file, i do: allWordsInFile.push_back(word);The file has a lot of duplicate words and I’m looking for ways to save memory. Each word needs to be represented in the correct position in the vector. I
Blackninja543
c memory
I have the following code which simply prints out an introduction for a person’s name.#include <stdio.h> #include <stdlib.h>typedef struct {char* firstname;char* lastname; }Person;void intro(void *person){printf(“The person you are looking for is %s %s\n”, ((Person *)person)->firstname, ((Person *)person)->lastname); }int main() {Person *a = NULL;a = (Person *)malloc(sizeof(Person));char *first = NULL, *last = NULL;first = (char *)malloc(sizeof(char)*20);strncpy(first,”Bob”, 20
loeschg
android memory jar garbage-collection espresso
When I include the espresso snapshot jar in my project, my gradle compilations hang and then kick out with the following message:UNEXPECTED TOP-LEVEL ERROR: java.lang.OutOfMemoryError: GC overhead limit exceededat java.util.Arrays.copyOf(Arrays.java:2219)at java.util.ArrayList.toArray(ArrayList.java:358)at java.util.ArrayList.<init>(ArrayList.java:164)at com.android.dx.ssa.SsaMethod.getUseListCopy(SsaMethod.java:660)at com.android.dx.ssa.ConstCollector.updateConstUses(ConstCollector.java:3
user583317
security memory malloc cuda gpgpu
I thought this was expected behavior?From: http://classic.chem.msu.su/cgi-bin/ceilidh.exe/gran/gamess/forum/?C35e9ea936bHW-7675-1380-00.htmParaphrased summary: “Working on the Linux port we found that cudaHostAlloc/cuMemHostAlloc CUDA API calls return un-initialized pinned memory. This hole may potentially allow one to examine regions of memory previously used by other programs and Linux kernel. We recommend everybody to stop running CUDA drivers on any multiuser system.”My understanding was t
ruakh
c++ memory object-persistence
I want to use pointer magikry to save a C++ class using the following method that writes byte data into a file:result Osp::Io::File::Write (const void *buffer, int length);Parameters:buffer – A pointer to the user-supplied buffer that contains byte data to be written length – The buffer length in bytesExceptions:E_SUCCESS – The method is successful. E_INVALID_STATE – The file has not been opened as yet. E_ILLEGAL_ACCESS – The file is not opened for write operation, or access is denied due to ins
Bill the Lizard
Thijs van Dien
delphi memory-management delphi-2010
I have a simple DLL written in Delphi. It provides functions which operate on some read-only data, embedded as a resource. I found loading that resource on each call to be quite slow, so I want to put it in an object that sticks around between calls.What is the right way to do this? The following works:varMyObject: TMyObject;function ReportSomethingAboutMyObject(): Integer; stdcall; export;exports ReportSomethingAboutMyObject();beginMyObject = TMyObject.Create;LoadTheResourceIntoObject(MyObject)
konrad
objective-c design-patterns memory-management
I need to implement a bit of functionality that can be used from a few different places in an application. It’s basically sending something over the network, but I don’t need it to be attached to any particular view – I can communicate everything to the user by UIAlertViews.What I would like to do is encapsulating the functionality in an object (?) that can maintain it’s own state for a while and then disappear all by itself. I’ve read in several similar topics that it’s generally not advised to
Poni
c cpu memory-management shared-memory
A quick question I’ve been wondering about for some time; Does the CPU assign values atomically, or, is it bit by bit (say for example a 32bit integer). If it’s bit by bit, could another thread accessing this exact location get a “part” of the to-be-assigned value?Think of this: I have two threads and one shared “unsigned int” variable (call it “g_uiVal”). Both threads loop. On is printing “g_uiVal” with printf(“%u\n”, g_uiVal). The second just increase this number. Will the printing thread ever
Manty
android memory-management linux-kernel arm page-fault
I am trying to debug a problem in which an application is triggering continuous data aborts due to invalid memory access.I have following queries.In general when an application in Android(CPU ARM) is accessing an invalid memory access, what happens?I guess a page fault would occur and then a data abort would be triggered. Is it so? Could someone briefly explain how does Android handle invalid memory access? What happens to the process which makes illegal memory access? Is it restarted again and
Arun
java web-services memory-management
I have the following code in my application which does two things:Parse the file which has ‘n’ number of data.For each data in the file, there will be two web service calls.public static List<String> parseFile(String fileName) {List<String> idList = new ArrayList<String>();try {BufferedReader cfgFile = new BufferedReader(new FileReader(new File(fileName)));String line = null;cfgFile.readLine();while ((line = cfgFile.readLine()) != null) {if (!line.trim().equals(“”)) {String []
Superman
c# .net memory-management garbage-collection heap
I have a large application which averages about 30 mb/sec in memory allocations (per performance monitor bytes allocated/sec measurement). I am trying to cut this down substantially, and the source of the allocations is not obvious.To instrument things I have recorded my ETW traces for the CLR / GC, and have exported the AllocationTick event, which records every time an additional 100 kilobytes is allocated, and what the object type was that was most recently allocated. This produces a nice size
Quinn Taylor
objective-c memory-management delegates
If class A is using class B and class A is class B’s delegate, is it ok if the delegate is set to nil in class B’s dealloc? I have seen code usually resetting the delegate to nil inside class A’s dealloc but wasn’t sure the real difference doing it one way or the other.e.g. This is the usual way:// somewhere in class A- (void) someFunc {self.b = [[B alloc] init];self.b.delegate = self; }- (void) dealloc {self.b.delegate = nil;[self.b release]; }
thetna
debugging memory memory-management memory-leaks valgrind
While searching about still reachable in valgrind, some people say its not a problem. we don’t nedd to fix it. Some people say it needs to be fixed.I would be better if somebody could exaplain me explicitly what is the logic behind this still reachable. Is it mandatory to fix this?[EDIT]I have following valgrind output for my C program.Do i need to fix it?LEAK SUMMARY:==27333== definitely lost: 0 bytes in 0 blocks.==27333== possibly lost: 0 bytes in 0 blocks.==27333== still reachable:
J Cooper
c++ memory-management deep-copy
Alright, so I’m trying out C++ for the first time, as it looks like I’ll have to use it for an upcoming course in college. I have a couple years of programming under my belt, but not much in the non-garbage-collected world.I have a class, a Node for use in a doubly linked list. So basically it has a value and two pointers to other Nodes. The main constructor looks like Node(const std::string & val, Node * prev, Node * next). The exercise includes a copy constructor that does a shallow copy o
hcpeter
c cygwin malloc
I have a strange error when try to malloc some memory. I’ve a pointer to a struct which is “malloced” and I want another struct. So I call malloc again and the pointer what malloc give back is point an empty space – so far it’s ok. Then I memset the allocated area and the memset overrides another variable which is still in use. The first struct in the memory is in 0x1643c98 and the given pointer to the second is 0x1643bf8 but I want to malloc 200 byte. The code:data_t *data = get_head_data();
user583317
security memory malloc cuda gpgpu
I thought this was expected behavior?From: http://classic.chem.msu.su/cgi-bin/ceilidh.exe/gran/gamess/forum/?C35e9ea936bHW-7675-1380-00.htmParaphrased summary: “Working on the Linux port we found that cudaHostAlloc/cuMemHostAlloc CUDA API calls return un-initialized pinned memory. This hole may potentially allow one to examine regions of memory previously used by other programs and Linux kernel. We recommend everybody to stop running CUDA drivers on any multiuser system.”My understanding was t
unwind
user3310133
c++ qt opengl malloc
I am with a issue in a QT + C++ +OpenGL project. The main problem is that I need to use a QText area to receive the number of cells in a array, but I’m not succeding. The fact is that, as the array is created within the moment my project starts to run I’d need to redifine it’s size, and then use it… I’ve already tried using realloc(to reallocate more memory to my array) after using free(), but when I try to do it my results are either a unexpected shut of the execution or a lot of crazy plots.
Piseagan
c linked-list malloc nodes
I’m writing a program that calls a function in main that creates a node to build a linked list. The program reads characters from a file to be placed in the nodes. The program runs fine until it gets into the function creating the nodes. I’m not sure if there is a logical or syntactical error or something else. Sorry for the length, but the errors aren’t far from the beginning. Also, let me know if you want my header file. The code is from my C book: Computer Science: A Structured Programm
user644371
c database memory pointers malloc
Solution: Allocated memory is freed up after a program exits. Have to read+write from disk back into a linked list, and then rewrite to update the database! Thank you everyone =)Hello, I’ve basically been working on this database program for the past few nights but I just continuously reach dead ends. The assignment is due today so if you could help me out, it would be very much appreciated. =TThe database is implemented with a Linked List and consists of a few files: sdbm.c, sdbm.h, new.c, get.
Burhan Ali
c memory-management malloc calloc
I know this question may be marked as a duplicate of difference between malloc and calloc but still i would like to ask it.i know calloc initilizes the memory block,here my question is not focusussing on that part.my question is the definition of malloc says it allocates a block of memory of specified size.and calloc says it allocates multiple block of memory ,each of the same size.is this allocation of one block of memory and multiple blocks of memory is a real difference between the two?becaus
c-urchin
c++ linux malloc valgrind glibc
I’m getting *** glibc detected *** (/my/program/…): malloc(): memory corruption: 0xf28000fa ***I’ve run under valgrind, which reports cases of reading memory that has been freed, but no cases of illegal memory writes. Could reading freed memory cause memory corruption? If not, any suggestions where else to look beyond the valgrind output?
Benoit
c malloc
Let me preface this by saying that i am a newbie, and im in a entry level C class at school. Im writing a program that required me to use malloc and malloc is allocating 8x the space i expect it to in all cases. Even when just to malloc(1), it is allocation 8 bytes instead of 1, and i am confused as to why. Here is my code I tested with. This should only allow one character to be entered plus the escape character. Instead I can enter 8, so it is allocating 8 bytes instead of 1, this is the ca
Ben Voigt
c++ size malloc
I have this code:char* str = (char*)malloc(27); int num = strlen(str);I have run the program in the debag mode and I have seen that num is equals to 40. why? why not 27?
AProgrammer
c++ delete overloading new-operator
Is it possible to put some restrictions in overloading operators new and delete? My overloaded new is linked in a different file to my test program.The scenario is:if(condition is satisfied)call overloaded new elsecall the actual new defined in new.h
Nick Strupat
c++ operator-overloading new-operator
I was thinking about some memory pool/allocation stuff I might write so I came up with this operator new overload that I want to use to facilitate reuse of memory. I’m wondering if there are any problems you guys can think of with my implementation (or any other possible ones).#include <cstddef>namespace ns {struct renew_t { };renew_t const renew; }template<typename T> inline void * operator new(std::size_t size, T * p, ns::renew_t renew_constant) {p->~T();return p; }template<t
ManuelSchneid3r
c++ new-operator
EDIT: I changed the title because it suited not nearly the problem, as the new operator was not the problem. The formerly title was “Can operator new fail?”In the code below, before a client connects to the server I create a new Socket object pointer. When a client connects I create the object with new. But somehow when I step through the code with the debugger (Eclipse CDT, g++ Ubuntu/Linaro 4.6.3-1ubuntu5) I see that after the call of the new operator the pointer ist still NULL.class Socket {
Columbo
c++ pointers heap new-operator
I’m having trouble understanding the following bit of code that I was hoping would create an array on the heap and fill it with the characters 9 down to 0 (I know I could just index the array like a normal stack array with [] notation to do this but I’m doing it this way to try to understand pointers in more depth):int *ptrHeapArray = new int[10]; for(int f=9; f>=0 ;f–){*ptrHeapArray = f;ptrHeapArray++;}for(int f=0; f<10; f++)cout << ptrHeapArray[f] << “\n”;It prints out comp
geraldCelente
c++ pointers null new-operator
I have a C++ class classA where I dynamically create an object instance of custom class classB through operator new.I have done this liretally hundreds of times successfull; however on this case the new operator is returning a NULL pointer, even though I have checked the values of the this pointer inside constructor and it is returning a non null pointer.I have created a class duplicating a minimum working example reproducing the fault. However, in this case the operator new works as expected.Fr
theDmi
c++ stack raii new-operator
I read in this blog, that making the new operator private is a good approach to enforce instantiation on the stack.I am implementing a class that employs the RAII idiom. This class should obviously only be instantiated on the stack, so I am looking for a way to enforce that.My question is, does this have any side effects that are not straight-forward to see? Is it a good approach to enforce instantiation on the stack? Are there any portability issues?Thanks for your help!EDITMy RAII class just
Yu Hao
c++ arrays memory-management new-operator
How is using ‘new’ considered dynamic? I understand that it gets put on the heap, returns a pointer and sticks around, but I don’t yet recognize it’s “dynamic” nature in terms of allocation.In the situations below, both arrays are allocated at runtime even the static method. So I don’t see a difference. And with both I don’t believe its possible to grow/shrink the allocation dynamically, correct?int size = 0; std::cout << “enter size: “; std::cin >> size;int* array_d = new int[size]
sonu thomas
java string object new-operator
I am new in java.In java, String is a class.But we do not have to use new keyword to create an object of class String where as new is used for creating objects for other classes.I have heard about Wrapper classes like Integer,Double which are similar to this. But String is not Wrapper,isn’t it?Actually what is happening when i useString message = “Hai”;?? How it is different from String message = new String(“Hai”);Here is message a reference variable or something else?? Are there other classes
dalle
language-design new-operator
Why does the new operator exist in modern languages such as C# and Java? Is it purely a self documenting code feature, or does it serve any actual purpose?For instance the following example:Class1 obj = new Class1();Class1 foo() {return new Class1(); }Is as easy to read as the more Pythonesque way of writing it:Class1 obj = Class1();Class1 foo() {return Class1(); }EDIT: Cowan hit the nail on the head with the clarification of the question: Why did they choose this syntax?
B?????
c++ malloc new-operator
In C (using gcc) I can declare a variable length struct as below:typedef struct ProtocolFrame {uint8_t op;uint32_t address;uint16_t size;uint8_t payload[0]; } ProtocolFrame;then I can alloc different frame:ProtocolFrame *frA; ProtocolFrame *frB;frA = malloc(sizeof(ProtocolFrame) + 50); frB = malloc(sizeof(ProtocolFrame));In this example frA has a payload field as big as 50 bytes, and frB has no payloadCan I do the same thing in C++ using the new operator?
Web site is in building