Memory Leak when Allocating a New Char Array (c string) - destructor

I am writing a program that uses character arrays / c strings. Whenever I run the program, valgrind throws a 'definitely lost' block warning:
==8011== [X] bytes in [Y] blocks are definitely lost in loss record 1 of [Z]
==8011== at 0x4A065BA: operator new[](unsigned long) (vg_replace_malloc.c:264)
==8011== by 0x403D45: File::File(stat*, char const*) (File.cpp:15)
...
This is the source code for the constructor and destructor (the header contains definitions for id, isDir, lastModified, and name (name is of type const char*)):
10 File::File(struct stat *statdat, const char* strName)
11 {
12 id = statdat->st_ino;
13 isDir = S_ISDIR(statdat->st_mode);
14 lastModified = (statdat->st_mtime);
15 char* tempName = new char[strlen(strName)+1];
16 strcpy(tempName, strName);
17 name = tempName;
18 tempName = NULL;
19 }
20
21 File::~File()
22 {
23 //delete [] name;
24 }
I have a couple questions with this.
a) Attempting to leave in delete in the destructor when compiling and running results in an instant crash due to an invalid pointer. Why can't I call delete on the character array?
b) I think I'm allocating the right amount of memory for the array. What is causing the memory leak when allocating new space? The error happens after the program stops (after valgrind's HEAP SUMMERY).

I have determined the issue.
My problem was with the /default/ constructor. Since it did not initialize 'name', the delete keyword was trying to delete a null pointer when the destructor was called on an object created by the default constructor. I modified my default constructor for File in order to initialize name to '\0', which appears to have solved the problem.

Related

How to pass arguments within a function in imageJ macro?

I want to pass in foldername into the run() function and the save() function but they are within quotes and I don't know how to pass the variable names.
I generated the run() and save() function using the record command in imageJ.
The aim of this program to to automate the process of running the plugin "T2 analysis mouse" on multiple folders.
Any other tweets or help will be appreciated.
I found this online source https://imagej.nih.gov/ij/macros/ArgumentPassingDemo.txt but it does not work.
I tried multiple ways inclusing /&foldername/3 T2 &filename/3 T2 /&foldername 3 T2``/&foldername3 T2 /&filename 3 T2``/&filename3 T2
Here is the code I wrote:
function makeT2(foldername)
{
filename = foldername;
print(filename);
run("T2 Analysis mouse", "select=[/Users/Vineeth/Desktop/New stuff Feb 5/&filename 3 T2]
image=[32-bit Signed] width=256 height=128 offset=0 number=902 gap=0 little-endian");
run("Save", "save=[/Users/Vineeth/Desktop/New stuff Feb 5/&foldername3 T2/T2map.tif]");
close();
}
folders = getFileList("/Users/Vineeth/Desktop/New stuff Feb 5/");
for( i = 0; i < folders.length; i++)
{
print(folders[i]);
file = getFileList("/Users/Vineeth/Desktop/New stuff Feb 5/" + folders[i]);
for( j = 0; j < file.length; j++)
{
if(file[j] == "3 T2/")
{
print("made t2 for " + folders[i] + file[j]);
makeT2(folders[i]);
}
}
}
The various print() functions are for testing the code and the code mostly works expect for the makeT2 function.
This is the error:
java.lang.NullPointerException
at T2_Analysis_mouse.getImage(T2_Analysis_mouse.java:183)
at T2_Analysis_mouse.run(T2_Analysis_mouse.java:56)
at ij.IJ.runUserPlugIn(IJ.java:183)
at ij.IJ.runPlugIn(IJ.java:150)
at ij.Executer.runCommand(Executer.java:124)
at ij.Executer.run(Executer.java:61)
at ij.IJ.run(IJ.java:249)
at ij.macro.Functions.doRun(Functions.java:561)
at ij.macro.Functions.doFunction(Functions.java:79)
at ij.macro.Interpreter.doStatement(Interpreter.java:203)
at ij.macro.Interpreter.doBlock(Interpreter.java:518)
at ij.macro.Interpreter.runUserFunction(Interpreter.java:278)
at ij.macro.Interpreter.doStatement(Interpreter.java:206)
at ij.macro.Interpreter.doBlock(Interpreter.java:518)
at ij.macro.Interpreter.doStatement(Interpreter.java:239)
at ij.macro.Interpreter.doIf(Interpreter.java:852)
at ij.macro.Interpreter.doStatement(Interpreter.java:215)
at ij.macro.Interpreter.doBlock(Interpreter.java:518)
at ij.macro.Interpreter.doStatement(Interpreter.java:239)
at ij.macro.Interpreter.doFor(Interpreter.java:464)
at ij.macro.Interpreter.doStatement(Interpreter.java:221)
at ij.macro.Interpreter.doBlock(Interpreter.java:518)
at ij.macro.Interpreter.doStatement(Interpreter.java:239)
at ij.macro.Interpreter.doFor(Interpreter.java:464)
at ij.macro.Interpreter.doStatement(Interpreter.java:221)
at ij.macro.Interpreter.doStatements(Interpreter.java:191)
at ij.macro.Interpreter.run(Interpreter.java:102)
at ij.macro.Interpreter.run(Interpreter.java:72)
at ij.macro.MacroRunner.run(MacroRunner.java:124)
at java.lang.Thread.run(Thread.java:695)
and this is the log after running the progran:
LeeMouseOld_30Jan18.LH1/
made t2 for LeeMouseOld_30Jan18.LH1/3 T2/
LeeMouseOld_30Jan18.LH1/
Please choose a directory where the T1 or T2 folder is the last item in the path (i.e. 5_t1 or 6_t2)
Directory return for General T folder: /Users/Vineeth/Desktop/New stuff Feb 5/&filename 3 T2/
Please adjust import settings to:
Image type: 32-bit signed
Width: 128 pixels
Height: 256 pixels
Number of images: 50 images
Check Little-endian byte order
As you can see &filename remains the same but I want the data within the variable filename to be in its place.
Use string concatenation:
run("T2 Analysis mouse", "select=[/Users/Vineeth/Desktop/New stuff Feb 5/" + filename + " 3 T2]
image=[32-bit Signed] width=256 height=128 offset=0 number=902 gap=0 little-endian");
run("Save", "save=[/Users/Vineeth/Desktop/New stuff Feb 5/" + foldername + "3 T2/T2map.tif]");
See the macro function documentation (emphasis added):
run("command"[, "options"])
Executes an ImageJ menu command. The optional second argument contains values that are automatically entered into dialog boxes (must be GenericDialog or OpenDialog). Use the Command Recorder (Plugins>Macros>Record) to generate run() function calls. Use string concatentation to pass a variable as an argument. With ImageJ 1.43 and later, variables can be passed without using string concatenation by adding "&" to the variable name. For examples, see the ArgumentPassingDemo macro.
The mentioned shortcut syntax with & does not work between square brackets [] in the option string.
A number of questions on the ImageJ forum also discuss this.

Failed to add fdf with attachment annotation

I work on an application to add annotation from a fdf file to a Pdf file
With iText can do in this way
FdfReader aFdfReader = new FdfReader(new FileInputStream(args[0]));
PdfReader aReader = new PdfReader(new FileInputStream(args[1]));
PdfStamper aStamper = new PdfStamper(aReader, new FileOutputStream(args[2]));
aStamper.addComments(aFdfReader);
aStamper.close();
But when i load the fdf I have this exception. The fdf have an annotation with the type attachment file.
Exception in thread "main" com.itextpdf.text.exceptions.InvalidPdfException: Error reading string at file pointer 5106590
at com.itextpdf.text.pdf.PRTokeniser.throwError(PRTokeniser.java:220)
at com.itextpdf.text.pdf.PRTokeniser.nextToken(PRTokeniser.java:411)
at com.itextpdf.text.pdf.PRTokeniser.nextValidToken(PRTokeniser.java:282)
at com.itextpdf.text.pdf.PdfReader.readPRObject(PdfReader.java:1908)
at com.itextpdf.text.pdf.PdfReader.readArray(PdfReader.java:1891)
at com.itextpdf.text.pdf.PdfReader.readPRObject(PdfReader.java:1946)
at com.itextpdf.text.pdf.PdfReader.readDictionary(PdfReader.java:1877)
at com.itextpdf.text.pdf.PdfReader.readPRObject(PdfReader.java:1913)
at com.itextpdf.text.pdf.PdfReader.readDocObj(PdfReader.java:1411)
at com.itextpdf.text.pdf.FdfReader.readPdf(FdfReader.java:105)
at com.itextpdf.text.pdf.PdfReader.(PdfReader.java:181)
at com.itextpdf.text.pdf.PdfReader.(PdfReader.java:395)
at com.itextpdf.text.pdf.PdfReader.(PdfReader.java:415)
at com.itextpdf.text.pdf.FdfReader.(FdfReader.java:92)
at com.artesys.pdf.itext.pdf.AddFdf.main(AddFdf.java:18)
I do the test with itext_so.pdf to attach to the annotation
if i made the test with a helloword i works fine
I used the version 5.5.9
Thank in advance for your response
Regards
Fabien
The FDF is special as it contains a PDF in a stream; this PDF stream is partially uncompressed; thus, PDF syntax, in particular PDF indirect object starts are visible.
And the FdfReader works incorrectly: It assumes these starts of indirect objects in a stream content to be top level FDF object starts and fails when trying to read those objects.
One can quick-fix this by making the FdfReader object reading more forgiving.
The FDF
Your FDF looks like this:
%FDF-1.2
%âãÏÓ
1 0 obj
<</FDF<</Annots[2 0 R]/F(http://localhost:8780/PachaServer/downloadpacha?pathpdf=Rendition.pdf&edit=false&loginname=fhfgh)/ID[<2175D5400E41761374A2EB01E7026C68><5E9C3BFFF121CE737ED66FF7318CA58D>]/UF(http://localhost:8780/PachaServer/downloadpacha?pathpdf=Rendition.pdf&edit=false&loginname=fhfgh)>>/Type/Catalog/Version/1.6>>
endobj
2 0 obj
<</C[0.25 0.333328 1.0]/Contents(itext_so.pdf)/CreationDate(D:20160519150439+02'00')/F 28/FS 3 0 R/M(D:20160519150439+02'00')/NM(79bcf116-d9bd-4ade-a8cd-7575351271fd)/Name/Paperclip/Page 0/RC(<?xml version="1.0"?><body xmlns="http://www.w3.org/1999/xhtml" xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/" xfa:APIVersion="Acrobat:15.16.0" xfa:spec="2.0.2" ><p>itext_so.pdf</p></body>)/Rect[183.106 684.663 190.106 701.663]/Subj(Pièce jointe)/Subtype/FileAttachment/T(Fabien.Levalois)/Type/Annot>>
endobj
3 0 obj
<</EF<</F 4 0 R>>/F(itext_so.pdf)/Type/Filespec/UF(itext_so.pdf)>>
endobj
4 0 obj
<</DL 10536008/Filter/FlateDecode/Length 10207532/Params<</CheckSum("}þ¶îô/Óý‡†d’ÒÎ)/CreationDate(D:20160511112202+02'00')/ModDate(D:20160511112205+02'00')/Size 10536008>>/Subtype/application#2Fpdf>>stream
... [10207532 data bytes] ...
endstream
endobj
trailer
<</Root 1 0 R>>
%%EOF
This structure is correct. But the contents of the big stream, the 10207532 data bytes in object 4 are special: They constitute a PDF document, and as this document already is compressed, it partially could not be compressed any further when embedded into the FDF and the original PDF syntax becomes piecewise visible, e.g. some 660000 bytes into the stream there suddenly are byte sequences which represent an end of the current PDF stream and the start of another indirect PDF object:
endstream
endobj
10283 0 obj
<</Extends 10282 0 R/Filter/FlateDecode/First 1139/Length 4195/N 100/Type/ObjStm>>stream
...
endstream
endobj
10284 0 obj
<</Extends 10282 0 R/Filter/FlateDecode/First 1139/Length 4018/N 100/Type/ObjStm>>stream
...
endstream
endobj
10285 0 obj
<</Extends 10282 0 R/Filter/FlateDecode/First 190/Length 1001/N 18/Type/ObjStm>>stream
etc. etc. etc.
As these PDF objects only are piecewise visible, though, trying to read them as is can result in an error.
The FdfReader
As an FDF does not need to contain a cross reference section, the FdfReader as a first step tries to create one by searching the file for byte sequences which appear to be the start of indirect objects and deriving a cross reference section from that.
This is incorrect, though, because in cases like your FDF it creates many false cross reference entries, and while reading these false indirect objects, errors occur unless the false objects are syntactically correct.
In case of your PDF many false objects are syntactically correct until a location near the offset 5106590 mentioned in the exception where a false indirect object is partially re-compressed. And when trying to reading that, FdfReader throws the exception you observed.
But the problem are not only such syntax errors (these could be caught and ignored after all) but that false objects and true objects may have the same object number. Thus, FdfReader might use a false object instead of a true one!
A quick fix
While the cross reference reconstruction code for the FdfReader fundamentally has to be re-implemented for a true fix, there is a quick fix for it allowing it to properly process FDFs in which the "false FDF objects" do not collide with true ones, simply derive a class from FdfReader and override the method readPRObject() like this:
#Override
protected PdfObject readPRObject() throws IOException
{
try
{
return super.readPRObject();
}
catch (InvalidPdfException e)
{
return PdfNull.PDFNULL;
}
}
(ImprovedFdfReader.java)
While reading the provided FDF itext-SO.fdf using the ReadFdf.java test method testReadFdfFabienLevalois with a normal FdfReader fails, doing so using the test method testReadFdfFabienLevaloisImproved with an ImprovedFdfReader succeeds.

Why do SOS/SOSEx misinterpret the values of a System.Collections.Generic.List.Enumerator?

I wrote a simple C# app:
static void Main(string[] args)
{
var list = new List<int> {500,400,300,200,100};
var listEnumerator = list.GetEnumerator();
listEnumerator.MoveNext();
} // <--- breakpoint here
I put a breakpoint at the end, ran it with Visual Studio, then fired up windbg and attached to the process (with the "non-invasive" checkbox turned on).
I then entered these commands:
.load C:\Program Files (x86)\Windows Kits\8.0\Debuggers\x86\sosex.dll
!mframe 17
!mdt listEnumerator
The output I got was clearly wrong (the fields are all messed up, it seems to report the value of 'index' under 'current', the value of 'current' under 'version', and the value of version' under 'index'. It got only one field right - the first one.
Local #0: (System.Collections.Generic.List`1+Enumerator) VALTYPE (MT=72dfd838, ADDR=0029efb8)
list:02632464 (System.Collections.Generic.List`1[[System.Int32, mscorlib]])
index:0x5 (System.Int32)
version:0x1f4 (System.Int32)
current:00000001 (T)
I then tried to use SOS's !DumpVC instead, and got the same confusion:
0:000> !DumpVC 72dfd838 0029efb8
Name: System.Collections.Generic.List`1+Enumerator
MethodTable: 72dfd838
EEClass: 72a32d38
Size: 24(0x18) bytes
File: C:\Windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll
Fields:
MT Field Offset Type VT Attr Value Name
736ae16c 4000c99 0 ...Generic.List`1[T] 0 instance 02632464 list
72e03aa4 4000c9a 8 System.Int32 1 instance 5 index
72e03aa4 4000c9b c System.Int32 1 instance 500 version
00000000 4000c9c 4 VAR 0 instance 00000001 current
Why does this happen?
The problem is that the CLR has re-ordered the fields of the enumerator struct for the closed type (enumerator of int) so that they don't match the open type (enumerator of T). Sosex was using the open type to read the fields instead of the closed type. This bug in sosex has now been fixed.

kdb c++ interface: create byte list from std::string

The following is very slow for long strings:
std::string s = "long string";
K klist = DBVec::CreateList(KG , s.length());
for (int i=0; i<s.length(); i++)
{
kG(klist)[i]=s.c_str()[i];
}
It works acceptably fast (<100ms) for strings up to 100k, but slows to a crawl (tens of minutes, possibly hours) for strings of a few million characters. I don't see anything other than kG that can create nonlinearity. I don't see any reason for accessor function kG to be non-constant time, but there is just nothing else in this loop. Unfortunately I don't know how kG works due to lack of documentation.
Question: given a blob of binary data as std::string, what's the efficient way to construct a byte list?
kG is a macro defined in k.h which expands to ((x)->G0), i.e. follow the G0 pointer of the K object
http://kx.com/q/d/a/c.htm#Strings documents kp, which creates a K string object directly from a string, so presumably you could do K klist = kp(s.c_str()), which is probably faster
This works:
memcpy(kG(klist), s.c_str(), s.length());
Still wonder why that loop is not O(N).

VirtualQuery gives illegal result. Is it a bug?

My code:
MEMORY_BASIC_INFORMATION meminf;
::VirtualQuery(box.pBits, &meminf, sizeof(meminf));
The results:
meminf:
BaseAddress 0x40001000 void *
AllocationBase 0x00000000 void *
AllocationProtect 0x00000000 unsigned long
RegionSize 0x0de0f000 unsigned long
State 0x00010000 unsigned long
Protect 0x00000001 unsigned long
Type 0x00000000 unsigned long
Notes:
(1) AllocationBase is NULL while BaseAddress is not NULL
(2) AllocationProtect is 0 (not a protection value)
Is it a bug of VirtualQuery?
This is not a bug. The documentation of VirtualQuery() states:
The return value is the actual number of bytes returned in the information buffer.
If the function fails, the return value is zero. To get extended error information, call GetLastError. Possible error values include ERROR_INVALID_PARAMETER.
Check the function result to be equal to sizeof(meminf) before using the data in the structure, or initialize the structure with values that will make the code that follows do the right thing. If the function returned 0 no data was copied to the structure, so it will still contain whatever data was previously in it. Without initialization this will be random bytes on the stack.
Passing a kernel-mode pointer to this function can result in no information being returned.
Check the return value.