Memory management code crashing - c++

I am making a GTA 5 mod using Scripthook. I ran their sample code with no issues, but when I try and make my own, it crashes the game.
#include "script.h"
#include "keyboard.h"
#include <string>
#include <ctime>
#pragma warning(disable : 4244 4305) // double <-> float conversions
#define ID 0
#define PED 1
LPINT currentPlayer() {
LPINT ret = (LPINT)malloc(sizeof(int) * 2);
ret[0] = PLAYER::PLAYER_ID();
ret[1] = PLAYER::PLAYER_PED_ID();
return ret;
}
void getPlayerCoords(LPVOID coords) {
*(Vector3 *)coords = ENTITY::GET_ENTITY_COORDS(currentPlayer()[PED], true);
}
void spawnKuruma2() {
Vector3 *currentCoordinates = (Vector3 *)malloc(sizeof(Vector3));
getPlayerCoords(currentCoordinates);
Hash kHash = GAMEPLAY::GET_HASH_KEY("KURUMA2");
STREAMING::REQUEST_MODEL(kHash);
while (!STREAMING::HAS_MODEL_LOADED(kHash));
Vehicle kuruma2 = VEHICLE::CREATE_VEHICLE(kHash, (*currentCoordinates).x + 5.0, (*currentCoordinates).y + 5.0, (*currentCoordinates).z, 0.0, true, true);
VEHICLE::SET_VEHICLE_ON_GROUND_PROPERLY(kuruma2);
STREAMING::SET_MODEL_AS_NO_LONGER_NEEDED(kHash);
ENTITY::SET_VEHICLE_AS_NO_LONGER_NEEDED(&kuruma2);
}
void main()
{
while (1)
{
if (IsKeyJustUp(VK_F8))
{
spawnKuruma2();
}
WAIT(0);
}
}
void ScriptMain()
{
srand(GetTickCount());
main();
}
I'm positive that it has something to do with the malloc call, but it looks fine to me. Can anyone point out what I could be doing wrong?

Related

C++ RasPi - Segmentation fault while in endless loop

So I run an DS18S20 with an LCD Display.
I'm measuring my Room Temperature and displaying it on the LCD.
In said endless loop, I'm getting a Segmentation Fault after it ran 5-6 times. I've read that it must be a variable and got the suspicion that it's in my getTmp() function but don't know how to fix it.
I've been learning C++ for two weeks now and need your help.
Thank you in advance.
My Code:
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <wiringPi.h>
#include <lcd.h>
#include <unistd.h>
using namespace std;
#define ever (;;)
//USE WIRINGPI PIN NUMBERS
#define LCD_RS 25 //Register select pin
#define LCD_E 24 //Enable Pin
#define LCD_D4 23 //Data pin 4
#define LCD_D5 22 //Data pin 5
#define LCD_D6 21 //Data pin 6
#define LCD_D7 14 //Data pin 7
void getTmp(string *y)
{
ifstream file("/sys/bus/w1/devices/10-00080366745a/w1_slave");
string f[2];
if (file.is_open())
{
for (int i = 0; i < 2; ++i)
{
getline(file, f[i]);
}
}
string s = f[1];
bool x = true;
int i3 = 0, i2 = 0;
while (x)
{
if (i2 <= 4 && i2 > 0)
{
y[i2 - 1] = s[i3];
++i2;
}
if (i2 > 4)
{
x = false;
}
if (s[i3] == '=')
{
i2 = 1;
}
++i3;
}
}
int main()
{
unsigned int microseconds = 5000;
string b[4];
string *y = b;
int lcd;
wiringPiSetup();
const char *tmp;
for ever
{
getTmp(y);
string t = "Temp = "+b[0]+b[1]+"."+b[2]+b[3]+"°C";
tmp=t.c_str();
lcd = lcdInit (2, 16, 4, LCD_RS, LCD_E, LCD_D4, LCD_D5, LCD_D6, LCD_D7, 0, 0, 0, 0);
lcdPuts(lcd, tmp);
cout << tmp << endl;
usleep(microseconds);
}
return 0;
}

Some problems with the functions GetCursorPos() and SetCursorPos() in C++

I am a new user of C++ and do not know all about types of variables.
I have this code but it doesn't work normally. For normal i mean - after starting cursor must be random moves for -25 to 25 pixel of screen.
Sorry if i provided few information. Ask me i can send what you want. And sorry for my bad English.
#include <iostream>
#include "MyForm1.h"
#include <windows.h>
#include <cstdlib>
#include <winuser.h>
#include <playsoundapi.h>
using namespace System;
using namespace System::Windows::Forms;
using namespace std;
// Cursor random moving here :3
int shakecursor() {
POINT p;
int __cdecl GetCursorPos(int &p);
cout << p.x << p.y << endl;
int x_p1;
int y_p1;
x_p1 = rand() % 0 -25;
y_p1 = rand() % 0 -25;
int x_p = p.x + x_p1;
int y_p = p.y + y_p1;
int __cdecl SetCursorPos(int x_p1, int y_p1);
Sleep(10);
return 0;
}
[STAThreadAttribute]
int main(cli::array<System::String ^> ^args) {
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
My3yPaB::MyForm mainForm;
Application::Run(%mainForm);
bool shaking = true;
while (shaking = true) {
shakecursor();
}
}```
These
int __cdecl GetCursorPos(int &p);
int __cdecl SetCursorPos(int x_p1, int y_p1);
are not function calls. they are function declarations.
Instead it seems you mean
GetCursorPos( p );
and
SetCursorPos( x_p, y_p );
So i fixed this problem and program doesn't do anything here code:
#include <iostream>
#include "MyForm1.h"
#include <windows.h>
#include <cstdlib>
#include <winuser.h>
#include <Mmsystem.h>
#include <playsoundapi.h>
#pragma comment (lib, "User32.lib")
using namespace System;
using namespace System::Windows::Forms;
using namespace std;
int shakecursor() {
POINT p;
GetCursorPos(&p);
cout << p.x << p.y << endl;
int x_p1;
int y_p1;
x_p1 = rand() % 51 - 25;
y_p1 = rand() % 51 - 25;
int x_p = p.x + x_p1;
int y_p = p.y + y_p1;
SetCursorPos(x_p, y_p);
Sleep(10);
return 0;
}
[STAThreadAttribute]
int main(cli::array<System::String ^> ^args) {
//PlaySound(L"start.mp3", NULL, NULL);
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
My3yPaB::MyForm mainForm;
Application::Run(%mainForm);
bool shaking = true;
while (shaking = true) {
shakecursor();
}
}```

How do I gtest that code did not call exit()

I'd like to test this function with Google Test:
foo() {
if(some_grave_error)
exit(1);
// do something
}
I want my test to fail if foo calls std::exit(). How do I do this? It is sort of inverse to what EXPECT_EXIT does?
You should make foo() testable:
using fexit_callback = void(*)(int);
void foo(fexit_callback exit = &std::exit)
{
if(some_condition)
exit(1);
}
And magically, all your troubles disappear:
#include <cstdlib>
#include <cassert>
using fexit_callback = void(*)(int);
void foo(fexit_callback exit = &std::exit)
{
if(true)
exit(1);
}
namespace mockup
{
int result = 0;
void exit(int r) { result = r; }
}
int main()
{
foo(mockup::exit);
assert(mockup::result == 1);
}

How to print the value stored in an char[] or string in the program itself

Have any one tried anything like this?
Is it possible to print the value of a string or integer on the program itself? Say for example - I have written 2 tests for a program I am trying to call all the tests functions by looping over in a for loop.
A small sample example
#define MAX_TESTS 10
for(test_idx = 0; test_idx<MAX_TESTS; ++test_idx)
{
test_##test_idx();
//Here the output will be more like "test_test_idx();"
//But I am looking for something like
//"test_0();"
//"test_1();"
//"test_2();"
.
.
.
//"test_9();"
}
Is there a way to do it in C?
Complete Program
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//Macros
#define MAX_TEST 2
#define _MYCAT(a,b) a##b()
void test_0()
{
printf("Test 0\n");
}
void test_1()
{
printf("Test 1 \n");
}
int main()
{
printf("Max Product Testing \n");
for (int test_idx=0; test_idx<MAX_TEST; ++test_idx)
{
/* Try - 1
char buffer[50];
int n = sprintf(buffer, "test_%d", test_idx);
printf("%s %d \n", buffer, n);
*/
//Try - 2
//_MYCAT(test_, test_idx);
}
return 0;
}
The closet you can get in C++ is to keep a map of function names to functions as follows:
#include <iostream>
#include <unordered_map>
#include <string>
#include <functional>
using namespace std;
void test_0()
{
printf("Test 0\n");
}
void test_1()
{
printf("Test 1 \n");
}
int main() {
unordered_map<string, function<void()>> func_map;
func_map["test_0"] = test_0;
func_map["test_1"] = test_1;
for(int i = 0; i < 2; ++i) {
func_map.at("test_" + to_string(i))();
}
return 0;
}
You can make an array of function pointers and call each one in a loop.
Example:
#include <stdio.h>
void test_0()
{
printf("Test 0\n");
}
void test_1()
{
printf("Test 1\n");
}
void test_2()
{
printf("Test 2\n");
}
int main()
{
void(*a)() = test_0;
void(*b)() = test_1;
void(*c)() = test_2;
const int SIZE = 3;
void(*arr[SIZE])() = {
{ a }, { b }, { c }
};
for (int i = 0; i < SIZE; ++i) {
arr[i]();
}
return 0;
}
Output:
Test 0
Test 1
Test 2

Field '__jmpbuf' could not be resolved -cpp

I get this error when trying to compile my program:
Field '__jmpbuf' could not be resolved
I looked for a solution for hours and can't seem to find out where is the culprit.
The Thread.h file contains the header of the class. It has the private member:
sigjmp_buf _env;
And the implementation is inside Thread.cpp:
#include "Thread.h"
#include <setjmp.h>
#include "translateAdd.h"
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <sys/time.h>
#define COUNTER_INIT -1
int Thread::_idCounter = COUNTER_INIT;
Thread::Thread(void (*threadsFunc)(void))
: threadsFunction(threadsFunc), _stack(new char[STACK_SIZE]), _quantums(1)
{
address_t sp, pc;
sp = (address_t)_stack + STACK_SIZE - sizeof(address_t);
pc = (address_t)threadsFunc;
// set environment for later return
sigsetjmp(_env, 1);
(_env->__jmpbuf)[JB_SP] = translate_address(sp);
(_env->__jmpbuf)[JB_PC] = translate_address(pc);
sigemptyset(&_env->__saved_mask);
_id = ++_idCounter;
_state = READY;
}
EDIT: Using eclipse as the IDE under ubuntu 32bit
EDIT: Another complete example that doesn't compile on my machine:
#include <stdio.h>
#include <setjmp.h>
#include <signal.h>
#include <unistd.h>
#include <sys/time.h>
#define SECOND 1000000
#define STACK_SIZE 4096
char stack1[STACK_SIZE];
char stack2[STACK_SIZE];
sigjmp_buf env[2];
#ifdef __x86_64__
/* code for 64 bit Intel arch */
typedef unsigned long address_t;
#define JB_SP 6
#define JB_PC 7
/* A translation is required when using an address of a variable.
Use this as a black box in your code. */
address_t translate_address(address_t addr)
{
address_t ret;
asm volatile("xor %%fs:0x30,%0\n"
"rol $0x11,%0\n"
: "=g" (ret)
: "0" (addr));
return ret;
}
#else
/* code for 32 bit Intel arch */
typedef unsigned int address_t;
#define JB_SP 4
#define JB_PC 5
/* A translation is required when using an address of a variable.
Use this as a black box in your code. */
address_t translate_address(address_t addr)
{
address_t ret;
asm volatile("xor %%gs:0x18,%0\n"
"rol $0x9,%0\n"
: "=g" (ret)
: "0" (addr));
return ret;
}
#endif
void switchThreads(void)
{
static int currentThread = 0;
int ret_val = sigsetjmp(env[currentThread],1);
printf("SWITCH: ret_val=%d\n", ret_val);
if (ret_val == 1) {
return;
}
currentThread = 1 - currentThread;
siglongjmp(env[currentThread],1);
}
void f(void)
{
int i = 0;
while(1){
++i;
printf("in f (%d)\n",i);
if (i % 3 == 0) {
printf("f: switching\n");
switchThreads();
}
usleep(SECOND);
}
}
void g(void)
{
int i = 0;
while(1){
++i;
printf("in g (%d)\n",i);
if (i % 5 == 0) {
printf("g: switching\n");
switchThreads();
}
usleep(SECOND);
}
}
void setup(void)
{
address_t sp, pc;
sp = (address_t)stack1 + STACK_SIZE - sizeof(address_t);
pc = (address_t)f;
sigsetjmp(env[0], 1);
(env[0]->__jmpbuf)[JB_SP] = translate_address(sp);
(env[0]->__jmpbuf)[JB_PC] = translate_address(pc);
sigemptyset(&env[0]->__saved_mask);
sp = (address_t)stack2 + STACK_SIZE - sizeof(address_t);
pc = (address_t)g;
sigsetjmp(env[1], 1);
(env[1]->__jmpbuf)[JB_SP] = translate_address(sp);
(env[1]->__jmpbuf)[JB_PC] = translate_address(pc);
sigemptyset(&env[1]->__saved_mask);
}
int main(void)
{
setup();
siglongjmp(env[0], 1);
return 0;
}
If you really need to use the internal fields (which will only be valid for your compiler on your system) you need to check the types:
typedef struct __jmp_buf_tag sigjmp_buf[1];
That means that sigjmp_buf is not a pointer, but an array with a single structure in it. So you use it like a normal array of structures:
sigjmp_buf _env;
_env[0].__jmpbuf[x] = y;
I really recommend against the use the internal field of this structure. Linux have other functions to simplify cooperative threading (which is what you seem to be implementing).