Occasional memory leak of VC++ console application with system("pause") - c++

OK. So this memory leak occurs randomly. And I tried to reproduce it in a simplified version of my original program. It's a VC++ console application with common header files for MFC.
The following is my memManager class, which originally is a image correction class that manages memory and also processes image.
typedef struct Point
{
int x;
int y;
}TPoint;
class memManager
{
public:
memManager();
~memManager();
void AllocMemory(TPoint **pAddr, int nSize);
void ReleaseMemory(TPoint **pAddr);
void ReleaseAllMemory();
TPoint* ptsPtr;
};
memManager::memManager()
{
ptsPtr = NULL;
}
memManager::~memManager()
{
ReleaseAllMemory();
}
void memManager::AllocMemory(TPoint **pAddr, int nSize)
{
if (*pAddr != NULL)
return;
TPoint *pTempAddr;
pTempAddr = new TPoint[nSize];
memset(pTempAddr, 0, sizeof(TPoint)*nSize);
*pAddr = pTempAddr;
return;
}
void memManager::ReleaseMemory(TPoint **pAddr)
{
if (*pAddr != NULL)
{
delete[] * pAddr;
*pAddr = NULL;
}
return;
}
void memManager::ReleaseAllMemory()
{
ReleaseMemory(&ptsPtr);
return;
}
And here is the the code in the main function.
memManager myMemManager;
myMemManager.AllocMemory(&myMemManager.ptsPtr,5000000);
system("pause");
When I debug the program, the console window shows with a prompt "Press any key to continue." And then I close the window by clicking the close button. One out of ten times, the output window of visual studio shows the following:
Detected memory leaks!
Dumping objects ->
{83} normal block at 0x000001FC942D9070, 40000000 bytes long.
Data: < > 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Object dump complete."
The program '[348] testForMemLeak.exe' has exited with code -1073741510 (0xc000013a).
I found it tricky to reproduce the result. Only if I clicked the close button right after the "busy" blue circle disappeared, should I get the memory leak message.
Is it because my memory handling function isn't good enough, or because the console application refused to call the destructor of memManager when I close the console window with bad timing?
Thanks.

Related

Unix domain socket bind failed in windows

I'm running the following code in order to create listener to unix domain socket.
Under macOS this code is working fine, but in Windows it produces the following error from the tcp_acceptor command : WSAEOPNOTSUPP
Here's a minimal reproducible example :
#include <iostream>
#include <boost/asio/local/stream_protocol.hpp>
constexpr char* kFileName = "file.sock";
using namespace std;
using namespace boost::asio;
int main(int argc, char* argv[])
{
io_context my_io_context;
::_unlink(kFileName); // Remove previous binding.
local::stream_protocol::endpoint server(kFileName);
local::stream_protocol::acceptor acceptor(my_io_context, server);
local::stream_protocol::socket socket(my_io_context);
acceptor.accept(socket);
return 0;
}
While debugging inside the boost library, i saw that the failure comes from the internal bind in the following code :
and this is the frame variables (it's clearly visible that sa_family = AF_UNIX (1):
I know that unix domain socket was introduced in windows10 few years ago, and i'm working with the latest version so it should be supported. Any idea what's wrong in my code?
EDIT : I've found out that in linux based machine I pass the following sockaddr to ::bind
(const boost::asio::detail::socket_addr_type) *addr = (sa_len = '\0', sa_family = '\x01', sa_data = "/tmp/server.sock")
(lldb) memory read addr
0x7ffeefbffa00: 00 01 2f 74 6d 70 2f 73 65 72 76 65 72 2e 73 6f ../tmp/server.so
0x7ffeefbffa10: 63 6b 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ck..............```
and in windows i get a slightly different struct :
{sa_family=1 sa_data=0x000000fffd33f682 "C:\\temp\\UnixSo... }const sockaddr *
Notice that the len field is missing in the windows platform.
Thanks
The issue seems to be the SO_REUSEADDR socket option, which ASIO by default sets. Setting this option itself succeeds, but causes the subsequent bind to fail.
Construct the acceptor with reuse_addr = false, then the binding should succeed:
local::stream_protocol::acceptor acceptor(my_io_context, server, false);

C++ not writing whole data to UART port

I have been testing UART communication in C++ with wiringPi.
The problem:
It seems that C++ isn't outputting whole data into the UART port /dev/ttyAMA0. Perhaps I'm doing it the wrong way?
Investigations:
Note : I am using minicom, minicom --baudrate 57600 --noinit --displayhex --device /dev/ttyAMA0 to check the received data.
Also! The UART port, RX & TX pins are shorted together.
The python code worked perfectly however when I tried to implement it in C++, the data received is different.
The expected received data should be: ef 01 ff ff ff ff 01 00 07 13 00 00 00 00 00 1b.
Received Data Comparison:
Language Used
Data Received from Minicom
Python
ef 01 ff ff ff ff 01 00 07 13 00 00 00 00 00 1b
C++
ef 01 ff ff ff ff 01
Code used
Python:
import serial
from time import sleep
uart = serial.Serial("/dev/ttyAMA0", baudrate=57600, timeout=1)
packet = [239, 1, 255, 255, 255, 255, 1, 0, 7, 19, 0, 0, 0, 0, 0, 27]
uart.write(bytearray(packet))
C++:
Note: Code compiled with g++ -Wall -O3 -o test hello.cpp -lwiringPi
#include <iostream>
#include <string.h>
#include <wiringPi.h>
#include <wiringSerial.h>
using namespace std;
int main()
{
int serial_port;
if (wiringPiSetup() == -1)
exit(1);
if ((serial_port = serialOpen("/dev/ttyAMA0", 57600)) < 0)
{
fprintf(stderr, "Unable to open serial device: %s\n", strerror(errno));
return 1;
}
cout << "Sending data to UART" << std::endl;
serialPuts(serial_port, "\xef\x01\xff\xff\xff\xff\x01\x00\x07\x13\x00\x00\x00\x00\x00\x1b");
return 0;
}
You can't use serialPuts to send the null terminator. As with all similar functions, it will stop when the null terminator is encountered in the string. In this case I think your best option is to add a function that uses the ordinary write function that is used internally by WiringPi's own functions.
You could make a wrapper function to make it look similar to the other calls:
#include <cstddef>
void serialWrite(const int fd, const char* data, size_t length) {
write(fd, data, length);
}
and perhaps a function template to not have to count the length of the data in the fixed data arrays manually:
template<size_t N>
void serialWrite(const int fd, const char(&data)[N], bool strip_last = true) {
serialWrite(fd, data, N - strip_last);
}
You can now use it like so:
serialWrite(serial_port, "\xef\x01\xff\xff\xff\xff\x01\x00\x07\x13\x00\x00\x00\x00\x00\x1b");
Note: There is a pull request to add a similar function (called serialPut) to the WiringPi library that you could download instead of using the official version from the master branch version if you don't want to make your own function.

Keyboard print UID MFRC522 Arduino Leonardo

I want to print the UID of a card as an HID with the Arduino Leonardo.
Here is the code that I have
void loop() {
if ( mfrc522.PICC_IsNewCardPresent()) {
// Select one of the cards
if ( mfrc522.PICC_ReadCardSerial()) {
// Dump debug info about the card; PICC_HaltA() is automatically called
mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
Keyboard.print(mfrc522.uid);
}
}
}
and this is what the compiler says
note: no known conversion for argument 1 from 'MFRC522::Uid' to 'const Printable&'
exit status 1
Does anyone know how to do it?
I believe that the isse you are facing is that you are trying to print a MFRC522::Uid which is a HEX number such as 00 00 00 00 while the keyboard.print() only accepts char, int or string according to: Arduino.cc. I found the following code snippet here. I believe it might resolve your issue. It should write: "Card UID: 00 00 00 00".
Serial.print("Card UID:"); //Dump UID
for (byte i = 0; i < mfrc522.uid.size; i++) {
Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
Serial.print(mfrc522.uid.uidByte[i], HEX);
}
NOTE: If you are using Keyboard.print() I believe you need to use Keyboard.begin() in your setup method.

ESP32 function from library is not called

I'm importing a a lib in my ESP32 project, this was originally designed for eclipse and imported into my code, using PlatformIO, putting it under lib:
Strange behaviour, if I activate the line:
errn = decode_dinExiDocument(&stream1, &exiDin1);
Code is compiled and executed but, no output from the function call is made, even the line:
Serial.println("dintest1");
At beginning of the function call to verify the method has been called.
If I remove call to decode_dinExiDocument everything is printed out correctly.
I'm little lost as I don't see any way to debug this. Any ideas?
#include <Arduino.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include "EXITypes.h"
#include "dinEXIDatatypes.h"
#include "dinEXIDatatypesEncoder.h"
#include "dinEXIDatatypesDecoder.h"
#define BUFFER_SIZE 256
uint8_t buffer1[BUFFER_SIZE];
uint8_t buffer2[BUFFER_SIZE];
static int din_test1(){
Serial.println("dintest1");
int errn = 0;
struct dinEXIDocument exiDin1;
struct dinEXIDocument exiDin2;
bitstream_t stream1;
bitstream_t stream2;
size_t pos1 = 0;
size_t pos2 = 0;
stream1.size = BUFFER_SIZE;
stream1.data = buffer1;
stream1.pos = &pos1;
stream2.size = BUFFER_SIZE;
stream2.data = buffer2;
stream2.pos = &pos2;
/* SetupSessionReq */
/* BMW: 80 9A 00 11 D0 20 00 03 C1 FC 30 00 43 F8 00 */
buffer1[0] = 0x80;
buffer1[1] = 0x9A;
buffer1[2] = 0x00;
buffer1[3] = 0x11;
buffer1[4] = 0xD0;
buffer1[5] = 0x20;
buffer1[6] = 0x00;
buffer1[7] = 0x03;
buffer1[8] = 0xC1;
buffer1[9] = 0xFC;
buffer1[10] = 0x30;
buffer1[11] = 0x00;
buffer1[12] = 0x43;
buffer1[13] = 0xF8;
buffer1[14] = 0x00;
//if i make this call method is not called and i get no output
errn = decode_dinExiDocument(&stream1, &exiDin1);
Serial.println(errn);
return errn;
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
}
void loop() {
// put your main code here, to run repeatedly:
printf("+++ Start simple DIN test +++\n");
int errn = din_test1();
printf("+++ Terminate simple DIN test with errn = %d +++\n\n", errn);
if(errn != 0) {
printf("\nDIN test error %d!\n", errn);
}
Serial.println("new loop");
delay(2000);
}
Also line that print "new loop" is not called but the delay is respected.
It is kind of impossible to answer to you without knowing what the function decode_dinExiDocument(&stream1, &exiDin1) does.
I see that the function comes from https://github.com/mhei/OpenV2G and that the library is in alpha release at the moment. I also noticed how the developers do not really like to put comments in their code.
First of all, I strongly advise you to have a look at this link: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-guides/error-handling.html
In particular, there are function calls to get a string out of an error code and redirect it to the serial port.
What is happening is a fatal error that resets your microcontroller. Is it possible that your function generates a memory leak, a stack overflow or that it tries to access a non initialized pointer?
It is also possible that the library internally uses some OS specific functions that try to allocate too much memory or that try to access some OS specific code which cannot be present on the ESP32?
Where did you call the "init" code for your structures? If you look at this header: https://github.com/mhei/OpenV2G/blob/master/src/din/dinEXIDatatypes.h you can easily see that there is a init_dinEXIDocument(struct dinEXIDocument* exiDoc); function to be called to initialize your structs before using them.
As a side note/personal opinion, I would never willingly use a function made of a giant switch statement with 81 uncommented and undocumented cases.
I solved problem.
code was right.
unfortunately memory heap allocation for thread was low so code hangs.
I leave the answer here if someone has similar problem

State Machine Problems

I am having a problem using a state machine setup. I am knew to these so I am having a problem. So there are some methods here can be ignored. The main problem is for some reason it sends a message for every byte it receives, but I thought Serial.read() clears the buffer after reading.
So here is the bulk of the code:
#include "Arduino_Structures.h"
#include <SPI.h>
#include <Ethernet.h>
#include "Time.h"
//GLOBAL DECLARATIONS
enum { STANDBY, SEND, RECEIVE, PROCESS} state = SEND;
enum { STATUS, CONFIG, CURRENT, TIME, VOLTAGE} messageType = STATUS;
char lcv;
char lcv2; //loop control variables
MESSAGE_STRUCT outgoing; //changing outgoing message
MESSAGE_STRUCT incoming; //changing incoming message
OODLES_BLOCK oodles; //oodles of information from the following 5 blocks
STATUS_BLOCK temp_status; //temporary status block
CONFIG_BLOCK temp_config; //temporary config block
CURRENT_BLOCK temp_current; //temporary current block
TIME_BLOCK temp_time; //temporary time block
VOLTAGE_BLOCK temp_voltage; //temporary voltage block
//FUNCATION DECLARATIONS
void sendMsg(MESSAGE_STRUCT* outgoing);
void receiveMsg(MESSAGE_STRUCT* incoming);
//ARDUINO SETUP
void setup()
{
delay(TIMEOUT); //wait for the boards to start up
Serial.begin(BAUD); //set the arduino to be at the Micro-AT baud rate
do
{
lcv = Ethernet.begin(mac); //start etherent board, get IP
}while(!lcv);
}
//ARDUINO LOOP
void loop()
{
switch(state)
{
case STANDBY:
delay(1000);
state = SEND;
break;
case SEND:
switch(messageType)
{
case STATUS:
outgoing.start_byte = 0x00;
outgoing.length = 0x00;
outgoing.address_1 = 0xFF;
outgoing.address_2 = 0xFF;
outgoing.code_word = REQUEST_STATUS;
outgoing.checksum = 0;
sendMsg(&outgoing);
state = RECEIVE;
break;
case CONFIG:
outgoing.start_byte = 0x00;
outgoing.length = 0x00;
outgoing.address_1 = 0xFF;
outgoing.address_2 = 0xFF;
outgoing.code_word = REQUEST_CONFIG;
outgoing.checksum = 0;
sendMsg(&outgoing);
state = RECEIVE;
break;
case CURRENT:
outgoing.start_byte = 0x00;
outgoing.length = 0x00;
outgoing.address_1 = 0xFF;
outgoing.address_2 = 0xFF;
outgoing.code_word = REQUEST_CURRENT;
outgoing.checksum = 0;
sendMsg(&outgoing);
state = RECEIVE;
break;
case TIME:
outgoing.start_byte = 0x00;
outgoing.length = 0x00;
outgoing.address_1 = 0xFF;
outgoing.address_2 = 0xFF;
outgoing.code_word = REQUEST_TIME;
outgoing.checksum = 0;
sendMsg(&outgoing);
state = RECEIVE;
break;
case VOLTAGE:
outgoing.start_byte = 0x00;
outgoing.length = 0x00;
outgoing.address_1 = 0xFF;
outgoing.address_2 = 0xFF;
outgoing.code_word = REQUEST_VOLTAGE;
outgoing.checksum = 0;
sendMsg(&outgoing);
state = RECEIVE;
break;
default:
break;
}
break;
case RECEIVE:
if(Serial.available())
{
state = SEND;
receiveMsg(&incoming);
//NEED TO CHECK TO MAKE SURRE START BYTE AND ADDRESS ARE CORRECT
//ALSO THIS IS WHERE I SHOULD CHECK THE CHECKSUM
//ONCE INSIDE SWITCHES NEED TO MAKE SURE THE RESPONSE IS CORRECT
switch(messageType)
{
case STATUS:
//copy information from incoming's data array to the temp_status block so that it retains its structure
memcpy(&temp_status, &incoming.data, sizeof(STATUS_BLOCK));
//these are directly taken from the status block information (Arduino_Structures.h)
oodles.left_source = temp_status.left_source;
oodles.right_source = temp_status.right_source;
oodles.left_overcurrent = temp_status.left_overcurrent;
oodles.right_overcurrent = temp_status.right_overcurrent;
oodles.automatic_transfer = temp_status.ready;
oodles.event_led = temp_status.event;
oodles.bus_type = temp_status.bus_type;
oodles.preferred = temp_status.preferred;
oodles.lockout_installed = temp_status.lockout_installed;
oodles.supervisory_control = temp_status.supervisory_control;
//put the time into the TimeElement then convert it to unix time
TimeElements timeInfo; //will be used (from Time.h library)
timeInfo.Year = temp_status.year;
timeInfo.Month = temp_status.month;
timeInfo.Day = temp_status.day;
timeInfo.Hour = temp_status.hour;
timeInfo.Minute = temp_status.minute;
timeInfo.Second = temp_status.second;
oodles.unix_time = makeTime(timeInfo);
//might want to wipe incoming and outogoing messages to make sure they get correctly rewritten
//messageType = CONFIG;
//state = SEND;
break;
case CONFIG:
break;
case CURRENT:
break;
case TIME:
break;
case VOLTAGE:
break;
}
}
break;
case PROCESS:
break;
}
}
void sendMsg(MESSAGE_STRUCT* message)
{
//brake up integers from MESSAGE_STRUCT to bytes (see intByte in Arduino_Structures.h)
intByte code_word, checksum;
code_word.intValue = message->code_word;
checksum.intValue = message->checksum;
//send byte by byte
Serial.write(message->start_byte);
Serial.write(message->length);
Serial.write(message->address_1);
Serial.write(message->address_2);
Serial.write(code_word.byte1);
Serial.write(code_word.byte2);
for(lcv = 0; lcv < message->length; lcv++)
Serial.write(message->data[lcv]);
Serial.write(checksum.byte1);
Serial.write(checksum.byte2);
}
void receiveMsg(MESSAGE_STRUCT* message)
{
//receive bytes and put them back as integers (see intByte in Arduino_Structures.h)
intByte code_word, checksum;
//receive byte by byte
message->start_byte = Serial.read();
message->length = Serial.read();
message->address_1 = Serial.read();
message->address_2 = Serial.read();
code_word.byte1 = Serial.read();
code_word.byte2 = Serial.read();
message->code_word = code_word.intValue;
for(lcv = 0; lcv < message->length; lcv++)
message->data[lcv] = Serial.read();
checksum.byte1 = Serial.read();
checksum.byte2 = Serial.read();
message->checksum = checksum.intValue;
}
And here is the Serial monitor showing the error, it should only respond once, and if I send it only one byte it responds once. If I send it an 8 byte response as below, it responds 8 times("Answer" means arduino to laptop, and "request" means laptop to arduino):
Answer: 6/26/2013 4:30:59 PM.56364 (+11.3133 seconds)
00 00 FF FF 00 01 00 00
Request: 6/26/2013 4:31:00 PM.48564 (+0.9219 seconds)
00 00 FF FF 01 01 00 00
Answer: 6/26/2013 4:31:00 PM.51664 (+0.0156 seconds)
00 00 FF FF 00 01 00 00 00 00 FF FF 00 01 00 00
00 00 FF FF 00 01 00 00 00 00 FF FF 00 01 00 00
00 00 FF FF 00 01 00 00 00 00 FF FF 00 01 00 00
00 00 FF FF 00 01 00 00 00 00 FF FF 00 01 00 00
It looks like you're checking to see that Serial.available() is not zero and then reading a bunch of data. It could be that you are not done recieving the data when you begin your receiveMsg function. You should:
Check to make sure that the bytes you need are available Wait if
They are not available, but you expect them to be coming soon
Just as an example:
void receiveMsg(MESSAGE_STRUCT* message)
{
// receive bytes and put them back as integers
intByte code_word, checksum;
// receive byte by byte, wait for it if need be
while( Serial.available() < 1 ) {delay(10);}
message->start_byte = Serial.read();
while( Serial.available() < 1 ) {delay(10);}
message->length = Serial.read();
There are better, more robust ways to do it, but this is pretty simple and easily implemented for a test to see if the input buffer is not getting filled.