Segmentation fault on XQueryTree - c++

I'm trying to close the last used window (the one right under the current window in the stacking order). Unfortunately XQueryTree segfaults for some reason.
#pragma once
#include <X11/Xlib.h>
#include <X11/Xutil.h>
namespace WindowingOperations {
inline void closeLastWindow() {
Display* dpy = XOpenDisplay(0);
Window root = DefaultRootWindow(dpy);
Window* root_return;
Window* parent_return;
Window** children_return;
unsigned int* nchildren_return;
XQueryTree(dpy,
root,
root_return,
parent_return,
children_return,
nchildren_return);
// Kill the window right after this one
if (*nchildren_return > 1)
XDestroyWindow(dpy, *children_return[*nchildren_return - 2]);
}
}
EDIT:
If you need a test case:
#include "window_operations.h"
int main() {
WindowingOperations::closeLastWindow();
return 0;
}

The _return parameters need somewhere to go. You can't just pass in uninitialized pointers, storage needs to be allocated for XQueryTree to write the results in.
So...
namespace WindowingOperations {
inline void closeLastWindow() {
Display* dpy = XOpenDisplay(0);
Window root = DefaultRootWindow(dpy);
// Allocate storage for the results of XQueryTree.
Window root_return;
Window parent_return;
Window* children_return;
unsigned int nchildren_return;
// then make the call providing the addresses of the out parameters
if (XQueryTree(dpy,
root,
&root_return,
&parent_return,
&children_return,
&nchildren_return) != 0)
{ // added if to test for a failed call. results are unchanged if call failed,
// so don't use them
// Kill the window right after this one
if (*nchildren_return > 1)
XDestroyWindow(dpy, *children_return[*nchildren_return - 2]);
}
else
{
// handle error
}
}
}

Related

Thread with expensive operations slows down UI thread - Windows 10, C++

The Problem: I have two threads in a Windows 10 application I'm working on, a UI thread (called the render thread in the code) and a worker thread in the background (called the simulate thread in the code). Ever couple of seconds or so, the background thread has to perform a very expensive operation that involves allocating a large amount of memory. For some reason, when this operation happens, the UI thread lags for a split second and becomes unresponsive (this is seen in the application as a camera not moving for a second while the camera movement input is being given).
Maybe I'm misunderstanding something about how threads work on Windows, but I wasn't aware that this was something that should happen. I was under the impression that you use a separate UI thread for this very reason: to keep it responsive while other threads do more time intensive operations.
Things I've tried: I've removed all communication between the two threads, so there are no mutexes or anything of that sort (unless there's something implicit that Windows does that I'm not aware of). I have also tried setting the UI thread to be a higher priority than the background thread. Neither of these helped.
Some things I've noted: While the UI thread lags for a moment, other applications running on my machine are just as responsive as ever. The heavy operation seems to only affect this one process. Also, if I decrease the amount of memory being allocated, it alleviates the issue (however, for the application to work as I want it to, it needs to be able to do this allocation).
The question: My question is two-fold. First, I'd like to understand why this is happening, as it seems to go against my understanding of how multi-threading should work. Second, do you have any recommendations or ideas on how to fix this and get it so the UI doesn't lag.
Abbreviated code: Note the comment about epochs in timeline.h
main.cpp
#include "Renderer/Headers/Renderer.h"
#include "Shared/Headers/Timeline.h"
#include "Simulator/Simulator.h"
#include <iostream>
#include <Windows.h>
unsigned int __stdcall renderThread(void* timelinePtr);
unsigned int __stdcall simulateThread(void* timelinePtr);
int main() {
Timeline timeline;
HANDLE renderHandle = (HANDLE)_beginthreadex(0, 0, &renderThread, &timeline, 0, 0);
if (renderHandle == 0) {
std::cerr << "There was an error creating the render thread" << std::endl;
return -1;
}
SetThreadPriority(renderHandle, THREAD_PRIORITY_HIGHEST);
HANDLE simulateHandle = (HANDLE)_beginthreadex(0, 0, &simulateThread, &timeline, 0, 0);
if (simulateHandle == 0) {
std::cerr << "There was an error creating the simulate thread" << std::endl;
return -1;
}
SetThreadPriority(simulateHandle, THREAD_PRIORITY_IDLE);
WaitForSingleObject(renderHandle, INFINITE);
WaitForSingleObject(simulateHandle, INFINITE);
return 0;
}
unsigned int __stdcall renderThread(void* timelinePtr) {
Timeline& timeline = *((Timeline*)timelinePtr);
Renderer renderer = Renderer(timeline);
renderer.run();
return 0;
}
unsigned int __stdcall simulateThread(void* timelinePtr) {
Timeline& timeline = *((Timeline*)timelinePtr);
Simulator simulator(timeline);
simulator.run();
return 0;
}
simulator.cpp
// abbreviated
void Simulator::run() {
while (true) {
// abbreviated
timeline->push(latestState);
}
}
// abbreviated
timeline.h
#ifndef TIMELINE_H
#define TIMELINE_H
#include "WorldState.h"
#include <mutex>
#include <vector>
class Timeline {
public:
Timeline();
bool tryGetStateAtFrame(int frame, WorldState*& worldState);
void push(WorldState* worldState);
private:
// The concept of an Epoch was introduced to help reduce mutex conflicts, but right now since the threads are disconnected, there should be no mutex locks at all on the UI thread. However, every 1024 pushes onto the timeline, a new Epoch must be created. The amount of slowdown largely depends on how much memory the WorldState class takes. If I make WorldState small, there isn't a noticable hiccup, but when it is large, it becomes noticeable.
class Epoch {
public:
static const int MAX_SIZE = 1024;
void push(WorldState* worldstate);
int getSize();
WorldState* getAt(int index);
private:
int size = 0;
WorldState states[MAX_SIZE];
};
Epoch* pushEpoch;
std::mutex lock;
std::vector<Epoch*> epochs;
};
#endif // !TIMELINE_H
timeline.cpp
#include "../Headers/Timeline.h"
#include <iostream>
Timeline::Timeline() {
pushEpoch = new Epoch();
}
bool Timeline::tryGetStateAtFrame(int frame, WorldState*& worldState) {
if (!lock.try_lock()) {
return false;
}
if (frame >= epochs.size() * Epoch::MAX_SIZE) {
lock.unlock();
return false;
}
worldState = epochs.at(frame / Epoch::MAX_SIZE)->getAt(frame % Epoch::MAX_SIZE);
lock.unlock();
return true;
}
void Timeline::push(WorldState* worldState) {
pushEpoch->push(worldState);
if (pushEpoch->getSize() == Epoch::MAX_SIZE) {
lock.lock();
epochs.push_back(pushEpoch);
lock.unlock();
pushEpoch = new Epoch();
}
}
void Timeline::Epoch::push(WorldState* worldState) {
if (this->size == this->MAX_SIZE) {
throw std::out_of_range("Pushed too many items to Epoch without clearing");
}
this->states[this->size] = *worldState;
this->size++;
}
int Timeline::Epoch::getSize() {
return this->size;
}
WorldState* Timeline::Epoch::getAt(int index) {
if (index >= this->size) {
throw std::out_of_range("Tried accessing nonexistent element of epoch");
}
return &(this->states[index]);
}
Renderer.cpp: loops to call Presenter::update() and some OpenGL rendering tasks.
Presenter.cpp
// abbreviated
void Presenter::update() {
camera->update();
// timeline->tryGetStateAtFrame(Time::getFrames(), worldState); // Normally this would cause a potential mutex conflict, but for now I have it commented out. This is the only place that anything on the UI thread accesses timeline.
}
// abbreviated
Any help/suggestions?
I ended up figuring this out!
So as it turns out, the new operator in C++ is threadsafe, which means that once it starts, it has to finish before any other threads can do anything. Why was that a problem in my case? Well, when an Epoch was being initialized, it had to initialize an array of 1024 WorldStates, each of which has 10,000 CellStates that need to be initialized, and each of those had an array of 16 items that needed to be initalized, so we ended up with over 100,000,000 objects needing to be initialized before the new operator could return. That was taking long enough that it caused the UI to hiccup while it was waiting.
The solution was to create a factory function that would build the pieces of the Epoch piecemeal, one constructor at a time and then combine them together and return a pointer to the new epoch.
timeline.h
#ifndef TIMELINE_H
#define TIMELINE_H
#include "WorldState.h"
#include <mutex>
#include <vector>
class Timeline {
public:
Timeline();
bool tryGetStateAtFrame(int frame, WorldState*& worldState);
void push(WorldState* worldState);
private:
class Epoch {
public:
static const int MAX_SIZE = 1024;
static Epoch* createNew();
void push(WorldState* worldstate);
int getSize();
WorldState* getAt(int index);
private:
Epoch();
int size = 0;
WorldState* states[MAX_SIZE];
};
Epoch* pushEpoch;
std::mutex lock;
std::vector<Epoch*> epochs;
};
#endif // !TIMELINE_H
timeline.cpp
Timeline::Epoch* Timeline::Epoch::createNew() {
Epoch* epoch = new Epoch();
for (unsigned int i = 0; i < MAX_SIZE; i++) {
epoch->states[i] = new WorldState();
}
return epoch;
}

Xlib : Segmentation fault on multithreading

My attempt is to write an Xlib wrapper for the purpose of implementing triple buffering methods. Using which a person needs only compute their display matrix and forward it to the API for displaying. I have two separate threads for handling events and display. The events thread seems to execute without any issue, however, the display thread, when used with standard Xlib functions such as XDrawRectangle, XFillArc, XSetForeground, etc. seems to cause a segmentation fault of an unknown nature.
This is my thread execution part :
int startx(){
pthread_t eventsThread, displayThread;
char msg1[15] ="Events Thread", msg2[15] = "Display Thread";
int pid1, pid2;
pid1 = pthread_create( &eventsThread, NULL, eventsHandler, (void*) msg1);
pid2 = pthread_create( &displayThread, NULL, displayHandler, (void*) msg2);
pthread_join(eventsThread, NULL);
pthread_join(displayThread, NULL);
return 0;
};
This is my displayHandler :
void *displayHandler(void* args){
cout<<connectionNumber<<endl;
Color c(50,50,250);
int width = 40, height = 60,x = 500, y = 100;
for(int i=0;i<1300;i++){
XSetForeground(display, xgraphics, c.decimal);
XDrawRectangle(display, mainWindow, xgraphics, x, y, width, height);
XFlush(display);
}
}
The eventsThread seems to be executing without error. Also, I have tried making the display function a part of the main program, with the same results.
If somebody could tell me an alternative/correct method to paint the window using matrices, it would be most appreciated.
Note : Color is a self made class for ease of colour computation.
This crashes for me before the howdy line. Uncommenting the return NULL; line makes it work.
#include <iostream>
#include <pthread.h>
void *displayHandler(void* args) {
char* txt = reinterpret_cast<char*>(args);
std::cout << txt << "\n";
// return NULL;
}
int startx(){
pthread_t displayThread;
char msg2[15] = "Display Thread";
int pid2;
pid2 = pthread_create( &displayThread, NULL, displayHandler, (void*) msg2);
pthread_join(displayThread, NULL);
return 0;
}
int main() {
startx();
std::cout << "howdy\n";
}
As Ted Lyngmo points out. The problem lay with the fact that Xlib has no thread safety implemented for writing to the display. So writing a mutex presented a solution.
If any of the event masks are set to write to the screen, separate threads for both become pointless. Instead making the masks toggle variables, allow them to work simultaneously.

Gtk/C++ Chronometer

I'm doing a game that uses a chronometer.
The game is written in C++ and I'm also using glade and GTK3.0
My problem is that when I start the game the chronometer doesn't work as it should..
I have created a file time.h with this code inside:
struct aTimer
{
bool running = false;
int hour_expired = 0;
int min_expired = 59;
int sec_expired = 50;
};
void start_time(aTimer *&t)
{
t->running = true;
}
void reset_time(aTimer *&t)
{
t->running = false;
t->sec_expired = 0;
t->min_expired = 0;
t->hour_expired = 0;
}
In my main file, I include it and also declare a new chronometer like this:
void start_time(aTimer *&);
void reset_time(aTimer *&);
aTimer *tempo = new aTimer;
Now, in my game, I have 2 windows, when i press play from the first window, the second window becomes visible and I hide the first one. When the second one is closed, the first becomes visible and the second invisible..
When the first window is closed, the application is closed.
In the struct, the bool running is false, because my idea was to make it true when you actually play the game (that is when you have the second window visible) and not at the start of the application..
So I've done this in the main file:
void start_game()
{
start_time(tempo);
}
gboolean update_time()
{
if (tempo->running)
{
if (tempo->sec_expired == 60)
{
tempo->sec_expired = 0;
(tempo->min_expired)++;
if (tempo->min_expired == 60)
{
tempo->min_expired = 0;
(tempo->hour_expired)++;
}
}
ostringstream oss;
GtkLabel *time = GTK_LABEL(gtk_builder_get_object(builder, "lblSec"));
oss<<(tempo->sec_expired)++;
gtk_label_set_text(time, oss.str().c_str());
oss.str("");
oss.clear();
time = GTK_LABEL(gtk_builder_get_object(builder, "lblMin"));
oss<<tempo->min_expired<<":";
gtk_label_set_text(time, oss.str().c_str());
oss.str("");
oss.clear();
time = GTK_LABEL(gtk_builder_get_object(builder, "lblHour"));
oss<<tempo->hour_expired<<":";
gtk_label_set_text(time, oss.str().c_str());
oss.str("");
oss.clear();
}
return tempo->running;
}
and in the main function of the main file i have also:
g_timeout_add_seconds(1, GSourceFunc(update_time), NULL);
If I start the application with the bool running = false, it won't work at all
If I start it the running = true, then it does work when i start the application, but as i come back to the "menu" and want to play another game, it won't start again.. The new time will just be the old time and won't increment anymore
I don't understand why though... Can someone help me?
Thank you
********************UPDATE************************
I tried the GTimer "option" as #José Fonte suggested but still can't come ahead..
This is an example that i tried..
#include <iostream>
#include <glib.h>
#include <sstream>
#include <gtk/gtk.h>
static GtkBuilder *builder;
using namespace std;
GTimer *timing;
bool start = false;
extern "C" void btnStartPause_click(GtkButton *button)
{
if (!start)
{
timing = g_timer_new();
start = true;
}
else
{
g_timer_stop(timing);
start = false;
}
}
gboolean update_time()
{
if (start)
{
gulong *micro;
double sec;
sec = g_timer_elapsed(timing, micro);
ostringstream oss;
GtkLabel *time = GTK_LABEL(gtk_builder_get_object(builder, "lblSec"));
oss<<(sec)++;
gtk_label_set_text(time, oss.str().c_str());
oss.str("");
oss.clear();
}
return start;
}
int main(int argc, char *argv[])
{
gtk_init(&argc, &argv);
builder = gtk_builder_new();
gtk_builder_add_from_file(builder,"glade.glade", NULL);
gtk_builder_connect_signals(builder, NULL);
// timing
g_timeout_add_seconds(1, GSourceFunc(update_time), NULL);
gtk_main();
return 0;
}
The problem again is.. I wanna start the timing when i click the btnStartPause button (not when i start the application), so i want it to start in the btnClick function..
But it seems like that the application tries instantly to do the gboolean update_time() function but since at the start of the application the boolean start is false, it just won't do the code, but when i click the button, so that the boolean start becomes true, it doesn't try again the gboolean update_time(), like it tried at the start of the application, and won't try it anymore.. I don't understand this..

Understanding unix child processes that use semaphore and shared memory

I'm going to do my best to ask this question with the understanding that I have.
I'm doing a programming assignment (let's just get that out of the way now) that uses C or C++ on a Unix server to fork four children and use semaphore and shared memory to update a global variable. I'm not sure I have an issue yet, but my lack of understanding has me questioning my structure. Here it is:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/sem.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define NUM_REPEATS 10
#define SEM_KEY 1111
#define SHM_KEY 2222
int globalCounter = 0;
/***** Test function for confriming a process type ******/
int checkProcessType(const char *whoami)
{
printf("I am a %s. My pid is:%d my ppid is %d\n",
whoami, getpid(), getppid() );
for(int i = 1; i<=3; i++){
printf("%s counting %d\n", whoami, i);
}
return 1;
}
void
int main (void) {
pid_t process_id; // PID (child or zero)
int sharedMemID; // Shared memory ID
int sharedMemSize; // shared memory size
struct my_mem * sharedMemPointer; // pointer to the attached shared memory
// Definition of shared memory //
struct my_mem {
long counter;
int parent;
int child;
};
// Gathering size of shared memory in bytes //
sharedMemSize = sizeof(my_mem);
if(sharedMemSize <= 0){
perror("error collection shared memory size: Exiting...\n");
exit(0);
}
// Creating Shared Memory //
sharedMemID = shmget(SHM_KEY, sharedMemSize, 0666 | IPC_CREAT);
if (sharedMemID < 0) {
perror("Creating shared memory has failed: Exiting...");
exit(0);
}
// Attaching Shared Memory //
sharedMemPointer = (struct my_mem *)shmat(sharedMemID, NULL, 0);
if (sharedMemPointer == (struct my_mem*) -1) {
perror("Attaching shared memory has failed. Exiting...\n");
exit(0);
}
// Initializing Shared Memory //
sharedMemPointer->counter = 0;
sharedMemPointer->parent = 0;
sharedMemPointer->child = 0;
pid_t adder, reader1, reader2, reader3;
adder = fork();
if(adder > 0)
{
// In parent
reader1 = fork();
if(reader1 > 0)
{
// In parent
reader2 = fork();
if(reader2 > 0)
{
//In parent
reader3 = fork();
if (reader3 > 0)
{
//In parent
}
else if (reader3 < 0)
{
// Error
perror("fork() error");
}
else
{
// In reader3
}
}
else if(reader2 < 0)
{
//Error
perror("fork() error");
}
else
{
// In reader2
}
}
else if(reader1 < 0)
{
// Error
perror("fork() error");
}
else
{
// In reader1
}
}
else if(adder < 0 )
{
// Error
perror("fork() error");
}
else
{
// In adder
//LOOP here for global var in critical section
}
}
Just some info of what I'm doing (I think), I'm creating a hunk of shared memory that will contain a variable, lets call it counter that will strictly be updated by adder and by the parent which becomes a subtractor after all child processes are active. I'm still trying to figure out the semaphore stuff that I will be using so adder and subtractor execute in critical section, but my main question is this.
How can I know where I am in this structure? My adder should have a loop that will do some job (update global var), and the parent/subtractor should have a loop for its job (also update global var). And all the readers can look at any time. Does the loop placement for parent/subtractor matter? I basically have 3 locations I know I'll be in parent. But since all children need to be created first does it have to be in the last conditional after my third fork where I know I'm in parent? When I use my test method I get scattered outputs, meaning child one can be after parent's output, then child three, etc. It's never in any order, and from what I understand of fork that's expected.
I really have like three questions going on, but I need to first wrap my head around the structure. So let me just try to say this again concisely without any junk cause I'm hung up on loop and critical section placement that isn't even written up yet.
More directly, when does parent know the existence of all children and with this structure can one child do a task and somehow come back to it (i.e. adder/first child adding to global variable once, exits, and some other child can do its thing etc).
I still feel like I'm not asking the right thing, and I believe this is due to still trying to grasp concepts. Hopefully my stammering will kind of show what I'm stuck on conceptually. If not I can clarify.

How do I get Fmod to work from a class?

In my project written in C++, I have FMOD currently working from my main.cpp. To help organize my engine I want to move my sound code to it's own translation unit. For some reason when I try to run my sound code from within my class, it doesn't play any sound. I'm not sure if it is because of incorrect assignment of the value or if there is a bigger issue that I don't know about. This is my class implementation:
//Sound.h
#ifndef SOUND_H
#define SOUND_H
#include <iostream>
#include "inc\fmod.hpp"
#include "inc\fmod_errors.h"
class Sound
{
public:
Sound(void);
~Sound(void);
void Init();
void FMODErrorCheck(FMOD_RESULT res);
void PlaySound();
void ResumeSound();
void PauseSound();
void Update();
private:
//sound
FMOD::System *sys;
FMOD_RESULT result;
size_t version; //this is just an unsigned int
FMOD_SPEAKERMODE speakerMode;
int numDrivers;
FMOD_CAPS caps;
char name[256];
FMOD::Sound *sound;
FMOD::Channel *channel;
bool quitFlag;
};
#endif
//Sound.cpp
#include "Sound.h"
Sound::Sound(void)
{
Init();
}
Sound::~Sound(void)
{
FMODErrorCheck(sound->release());
FMODErrorCheck(sys->release());
}
void Sound::Init()
{
// Create FMOD interface object
result = FMOD::System_Create(&sys);
FMODErrorCheck(result);
// Check version
result = sys->getVersion(&version);
FMODErrorCheck(result);
if(version < FMOD_VERSION)
{
std::cout << "Error! You are using an old version of FMOD " << version << ". This program requires " << FMOD_VERSION << std::endl;
exit(0);
}
// Get number of sound cards
result = sys->getNumDrivers(&numDrivers);
FMODErrorCheck(result);
// No sound cards (disable sound)
if(numDrivers == 0)
{
result = sys->setOutput(FMOD_OUTPUTTYPE_NOSOUND);
FMODErrorCheck(result);
}
// At least one sound card
else
{
// Get the capabilities of the default (0) sound card
result = sys->getDriverCaps(0, &caps, 0, &speakerMode);
FMODErrorCheck(result);
// Set the speaker mode to match that in Control Panel
result = sys->setSpeakerMode(speakerMode);
FMODErrorCheck(result);
// Increase buffer size if user has Acceleration slider set to off
if(caps & FMOD_CAPS_HARDWARE_EMULATED)
{
result = sys->setDSPBufferSize(1024, 10);
FMODErrorCheck(result);
}
// Get name of driver
result = sys->getDriverInfo(0, name, 256, 0);
FMODErrorCheck(result);
// SigmaTel sound devices crackle for some reason if the format is PCM 16-bit.
// PCM floating point output seems to solve it.
if(strstr(name, "SigmaTel"))
{
result = sys->setSoftwareFormat(48000, FMOD_SOUND_FORMAT_PCMFLOAT, 0, 0, FMOD_DSP_RESAMPLER_LINEAR);
FMODErrorCheck(result);
}
}
// Initialise FMOD
result = sys->init(100, FMOD_INIT_NORMAL, 0);
// If the selected speaker mode isn't supported by this sound card, switch it back to stereo
if(result == FMOD_ERR_OUTPUT_CREATEBUFFER)
{
result = sys->setSpeakerMode(FMOD_SPEAKERMODE_STEREO);
FMODErrorCheck(result);
result = sys->init(100, FMOD_INIT_NORMAL, 0);
}
FMODErrorCheck(result);
// Open music as a stream
//FMOD::Sound *song1, *song2, *effect;
//result = sys->createStream("Effect.mp3", FMOD_DEFAULT, 0, &sound);
//FMODErrorCheck(result);
result = sys->createSound("Effect.mp3", FMOD_DEFAULT, 0, &sound);
FMODErrorCheck(result);
// Assign each song to a channel and start them paused
//result = sys->playSound(FMOD_CHANNEL_FREE, sound, true, &channel);
//FMODErrorCheck(result);
// Songs should repeat forever
channel->setLoopCount(-1);
}
void Sound::FMODErrorCheck(FMOD_RESULT res)
{
if(res != FMOD_OK)
{
std::cout << "FMOD ERROR: (" << res << ") - " << FMOD_ErrorString(res) << std::endl;
//quitFlag = true;
}
}
void Sound::PlaySound()
{
sys->playSound(FMOD_CHANNEL_FREE, sound, false, 0);
}
void Sound::ResumeSound()
{
channel->setPaused(false);
}
void Sound::PauseSound()
{
channel->setPaused(true);
}
void Sound::Update()
{
sys->update();
}
//Main.cpp
Sound sound;
// Initialization routine.
void setup(void)
{
glClearColor(0.0, 0.0, 0.0, 0.0);
sound = &Sound();
}
//------------------------------------------------------------ OnInit()
//
void OnIdle()
{
if(IsKeyPressed(KEY_ESCAPE))
{
exit(EXIT_SUCCESS);
}
if(IsKeyPressed('1'))
{
sound->PlaySound();
}
sound->Update();
// redraw the screen
glutPostRedisplay();
}
Currently it is giving me 2 errors:
Unhandled exception at 0x0F74465A (fmodex.dll) in TestOpenGL.exe: 0xC0000005: Access violation reading location 0x062C5040
and
FMOD error! (36) An invalid object handle was used
Any idea why it isn't working? Any idea how I solve these issues?
From your last comment and looking at your code I see a problem. You have created a pointer by FMOD::System *sys; but this pointer is not initialized to any instance of FMOD::System that is, there should be something like sys = new FMOD::System or sys = new FMOD::System(/* whatever argument you must supply to it's constructor */); somewhere in your code but right before you try to access anything related to FMOD::System object. This is most probably the reason for your program crash. Also since sys is a pointer to FMOD::System there's another problem at line containing result = FMOD::System_Create(&sys); you are passing a pointer by reference. I suggest you read a couple of articles about pointers in C and C++ and also some more about object creation and destruction in object oriented programming languages.
I was able to get help with the issue. I was initializing my sound variable incorrectly.
sound = &Sound();
Should actually be:
sound = new Sound();