Pass an array or argptr as parameters to a old varargs (...) function? C++ - c++

I have a old varargs(...) function that uses va_list, va_start, va_arg, va_end
cell executeForwards(int id, ...)
{
if (!g_forwards.isIdValid(id))
return -1;
cell params[FORWARD_MAX_PARAMS];
int paramsNum = g_forwards.getParamsNum(id);
va_list argptr;
va_start(argptr, id);
ForwardParam param_type;
for (int i = 0; i < paramsNum && i < FORWARD_MAX_PARAMS; ++i)
{
param_type = g_forwards.getParamType(id, i);
if (param_type == FP_FLOAT)
{
REAL tmp = (REAL)va_arg(argptr, double); // floats get converted to doubles
params[i] = amx_ftoc(tmp);
}
else if(param_type == FP_FLOAT_BYREF)
{
REAL *tmp = reinterpret_cast<REAL *>(va_arg(argptr, double*));
params[i] = reinterpret_cast<cell>(tmp);
}
else if(param_type == FP_CELL_BYREF)
{
cell *tmp = reinterpret_cast<cell *>(va_arg(argptr, cell*));
params[i] = reinterpret_cast<cell>(tmp);
}
else
params[i] = (cell)va_arg(argptr, cell);
}
va_end(argptr);
return g_forwards.executeForwards(id, params);
}
For some reason I need to push the parameters dynamically to this function, for example by using an array or something, Is that possible in C++?
example code:
va_list argptr;
va_push(argptr, 100);
va_push(argptr, 2.22f);
va_push(argptr, 300);
executeForwards(0, argptr);
Notice: I cannot modify the content of this function (executeForwards)

Related

Passing char pointer to function ruins pointer

I am having some difficulties with a bluetooth/oled display displaying the right string. The goal is to read data from bluetooth, update a class variable(Music.setArtist()), and then read from that variable later(Music.getArtist()) to draw it using a draw text function.
If i only call drawText once, it works fine. More than one calls in a loop to drawText cause some undefined behavior though, which is usually the second pointer getting overwritten. This causes the pointer in drawText to be null, or some random characters, or something.
This is my music object.
#ifndef Music_h
#define Music_h
class Music {
private:
char *track,*artist,*length, *position;
int progressBar;
bool playing;
public:
Music(char* t, char* a, char* l, char* po, bool pl, int p): track(t), artist(a), length(l), position(po), playing(pl), progressBar(p){};
~Music(){};
char* getLength(){return length;}
char* getPosition(){return position;}
char* getArtist(){return artist;}
char* getTrack(){return track;}
bool getPlaying(){return playing;}
int getProgressBar(){return progressBar;}
void setLength(char * l){length = l;}
void setPosition(char *p){position = p;}
void setArtist(char *a){artist = a;}
void setTrack(char *t){track = t;}
void setPlaying(bool p){playing = p;}
void setProgressBar(int p){progressBar = p;}
};
#endif
This is my drawText function
void Display_obj::drawText(double xPos, double yPos,char str[], int stringSize, uint8_t asciiBuff)
{
bitmapLetter fnt_controller(0,0,0x00,0,0);
bitmapLetter sheldon_alph[0x5A];
fnt_controller.createDictionary(sheldon_alph,6,8);
int startX = xPos;
int startY = yPos;
for (int i=0; i < stringSize; i++){
char charAt = str[i];
uint8_t ascii = (uint8_t)charAt;
if (ascii > 0x60)
{
charAt = charAt & ~(0x20);
ascii = ascii & ~(0x20);
}
int width = sheldon_alph[ascii-asciiBuff].getWidth();
int height = sheldon_alph[ascii-asciiBuff].getHeight();
size_t siz = sheldon_alph[ascii-asciiBuff].getSize();
unsigned char* bitmap = sheldon_alph[ascii-asciiBuff].getLetter();
drawBitmap(startX,startY,width,height,bitmap,siz);
startX = startX - 8;
if (startX <= 0)
{
startX = xPos;
startY = startY+8;
}
}
}
and my main loop looks something like this
Music music("", "", "", "", false, 0);
RideTracking ride("", "", "", "", "", false);
Navigation nav("", "", "", "", "", false);
void loop(){
if (bt.getDataUpdated() == false)
{
bt.recvWithEndMarker(&bt,&music);
}
else
{
//Serial.println(music.getTrack());
musicUpdateTrack(music.getTrack());
//Serial.println(music.getArtist()); --> This returns gibberish. If the above update is commented out, it works.
musicUpdateArtist(music.getArtist());
bt.setDataUpdated(false);
}
}
Ive tried everything i can think of, which was a lot of messing around with pointers and addresses to see if it was allocated correctly. This is the closest ive gotten, but it seems like the drawText breaks the rest of the char pointers i call in the future. I dont believe the issue has to do with flash or SRAM, as both seem to be within normal values. Any help would be greatly appreciated.
EDIT: in my bluetooth object, there are two calls. one is receive the data, and the other updates the object. I originally didnt include this as it looks like data is set correctly. if i dont call drawtext, but just call print statements, the data is correct.
void blue::updateData(Music* music) {
if (getDataUpdated() == true) {
StaticJsonDocument<256> doc;
DeserializationError error = deserializeJson(doc, receivedChars);
else{
char s1[55];
char s2[55];
char s3[15];
char s4[15];
char s5[15];
if(doc["music"]) {
strlcpy(s1, doc["music"]["track"]);
music->setTrack(s1);
strlcpy(s2, doc["music"]["artist"]);
music->setArtist(s2);
strlcpy(s3, doc["music"]["track_length"]);
music->setLength(s3);
strlcpy(s4, doc["music"]["position"]);
music->setPosition(s4);
music->setProgressBar(doc["music"]["progressBar"]);
music->setPlaying(doc["music"]["playing"]);
}
}
void blue::recvWithEndMarker(blue* bt,Music* mu) {
char rc;
while (ble.available() > 0 && getDataUpdated() == false) {
rc = ble.read();;
if (rc != endMarker)
{
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars)
{
ndx = numChars - 1;
}
}
else
{
brackets++;
if(brackets != 2)
{
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars)
{
ndx = numChars - 1;
}
}
else
{
receivedChars[ndx] = rc;
receivedChars[ndx+1] = '\0'; // terminate the string
ndx = 0;
brackets = 0;
setDataUpdated(true);
}
}
}
bt->updateData(mu);
}
Found it! In the music class, i changed the variables such as *track, to a hardset track[50]. Then, in the set method, i changed it to
void setLength(char * l){
strlcpy(length,l,strlen(l)+1);
}
void setPosition(char *p){
strlcpy(position,p,strlen(p)+1);
}
void setArtist(char *a){
strlcpy(artist,a,strlen(a)+1);
}
void setTrack(char *t){
strlcpy(track,t,strlen(t)+1);
}
Along with a few changes in how its passed, it now works. Thanks! Ive been stuck on this for days.

Creating a second instance of an object changes whole class behavior (C++)

I have written an Arduino library in C++ that contains an iterator class. If I iterate through it using the same instance all the time, it works as expected. If I create a second instance to do so, it will double the amount of stored objects.
WayPointStack wps = *(new WayPointStack());
wps.AddWP(1, 20);
wps.AddWP(2, 420);
WPCommand c1 = wps.GetNextWP(); // Stack length: 2, correct
c1 = wps.GetNextWP(); //
WPCommand c1 = wps.GetNextWP(); // Stack length: 4, not correct
WPCommand c2 = wps.GetNextWP(); //
WPCommand WayPointStack::GetNextWP()
{
Serial.println("Pointer = ");
Serial.println(pointer);
Serial.println("Length = ");
Serial.println(_length);
if (pointer < _length){
pointer++;
return _wp[pointer-1];
}
return *(new WPCommand(_END, 10000));
}
void WayPointStack::AddWP(int target, int time)
{
if (_length == arrSize)
return;
_wp[_length] = *(new WPCommand(target, time));
_length++;
}
WayPointStack::WayPointStack()
{
_wp = new WPCommand[arrSize];
_length = 0;
pointer = 0;
}
WPCommand::WPCommand(int target, int time)
{
_target = target;
_time = time;
}
Can someone explain this to me?
WayPointStack wps = *(new WayPointStack());
must be
WayPointStack wps;
because it is enough and that removes the memory leak
In
WPCommand WayPointStack::GetNextWP()
{
...
return *(new WPCommand(_END, 10000));
}
you create an other memory leak, may be do not return the element but its address allowing you to return nullptr on error ?
/*const ?*/ WPCommand * WayPointStack::GetNextWP()
{
Serial.println("Pointer = ");
Serial.println(pointer);
Serial.println("Length = ");
Serial.println(_length);
if (pointer < _length){
return &_wp[pointer++];
}
return nullptr;
}
else use a static var :
WPCommand WayPointStack::GetNextWP()
{
...
static WPCommand error(_END, 10000);
return error;
}
In
void WayPointStack::AddWP(int target, int time)
{
if (_length == arrSize)
return;
_wp[_length] = *(new WPCommand(target, time));
_length++;
}
you create an other memory leak, you just need to initialize the entry :
void WayPointStack::AddWP(int target, int time)
{
if (_length == arrSize)
return;
_wp[_length]._target = target, time));
_wp[_length]._time = time;
_length++;
}
you do not signal the error when you cannot add a new element, what about to return a bool valuing false on error and true when you can add :
bool WayPointStack::AddWP(int target, int time)
{
if (_length == arrSize)
return false;
_wp[_length]._target = target;
_wp[_length]._time = time;
_length++;
return true;
}
Finally Why do you not use a std::vector for _wp
It looks like you have a memory leak on this line:
return *(new WPCommand(_END, 10000));
It looks like you are creating WPCommand on heap, then throw away pointer and return a copy !!!
The example is not minimal and complete so it is hard to give better pointers.

C++ linked list has junk nodes appearing in it [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
When implementing a call stack trace for tracking allocation in my overridden new function, I am using ::malloc to create an untracked call stack object that is then put into a linked list. When my harness finishes new-ing off all of the test cases, the list is sound. However, when i go to report the list (print to console) there are now values that should not be there and are causing it to crash. Below is the simplified version (I apologize that even simplified it is still a lot of code), I am hoping someone can make since of this:
Macros
#define convertToKiB(size) size * 1024UL
#define convertToMiB(size) size * (1024UL * 1024UL)
#define convertToGiB(size) size * (1024UL * 1024UL * 1024UL)
#define convertToReadableBytes(size) ((uint32_t)size > convertToKiB(2) && (uint32_t)size < convertToMiB(2)) ? (float)size / (float)convertToKiB(1) : ((uint32_t)size > convertToMiB(2) && (uint32_t)size < convertToGiB(2)) ? (float)size / (float)convertToMiB(1) : ((uint32_t)size > convertToGiB(2)) ? (float)size / (float)convertToMiB(1) : (float)size
#define convertToReadableBytesString(size) ((uint32_t)size > convertToKiB(2) && (uint32_t)size < convertToMiB(2)) ? "KiB" : ((uint32_t)size > convertToMiB(2) && (uint32_t)size < convertToGiB(2)) ? "MiB" : ((uint32_t)size > convertToGiB(2)) ? "GiB" : "B"
Globals
const uint8_t MAX_FRAMES_PER_CALLSTACK = 128;
const uint16_t MAX_SYMBOL_NAME_LENGTH = 128;
const uint32_t MAX_FILENAME_LENGTH = 1024;
const uint16_t MAX_DEPTH = 128;
typedef BOOL(__stdcall *sym_initialize_t)(IN HANDLE hProcess, IN PSTR UserSearchPath, IN BOOL fInvadeProcess);
typedef BOOL(__stdcall *sym_cleanup_t)(IN HANDLE hProcess);
typedef BOOL(__stdcall *sym_from_addr_t)(IN HANDLE hProcess, IN DWORD64 Address, OUT PDWORD64 Displacement, OUT PSYMBOL_INFO Symbol);
typedef BOOL(__stdcall *sym_get_line_t)(IN HANDLE hProcess, IN DWORD64 dwAddr, OUT PDWORD pdwDisplacement, OUT PIMAGEHLP_LINE64 Symbol);
static HMODULE g_debug_help;
static HANDLE g_process;
static SYMBOL_INFO* g_symbol;
static sym_initialize_t g_sym_initialize;
static sym_cleanup_t g_sym_cleanup;
static sym_from_addr_t g_sym_from_addr;
static sym_get_line_t g_sym_get_line_from_addr_64;
static int g_callstack_count = 0;
static callstack_list* g_callstack_root = nullptr;
CallStack Object
struct callstack_line_t
{
char file_name[128];
char function_name[256];
uint32_t line;
uint32_t offset;
};
class CallStack
{
public:
CallStack();
uint32_t m_hash;
uint8_t m_frame_count;
void* m_frames[MAX_FRAMES_PER_CALLSTACK];
};
CallStack::CallStack()
: m_hash(0)
, m_frame_count(0) {}
bool CallstackSystemInit()
{
// Load the dll, similar to OpenGL function fecthing.
// This is where these functions will come from.
g_debug_help = LoadLibraryA("dbghelp.dll");
if (g_debug_help == nullptr) {
return false;
}
// Get pointers to the functions we want from the loded library.
g_sym_initialize = (sym_initialize_t)GetProcAddress(g_debug_help, "SymInitialize");
g_sym_cleanup = (sym_cleanup_t)GetProcAddress(g_debug_help, "SymCleanup");
g_sym_from_addr = (sym_from_addr_t)GetProcAddress(g_debug_help, "SymFromAddr");
g_sym_get_line_from_addr_64 = (sym_get_line_t)GetProcAddress(g_debug_help, "SymGetLineFromAddr64");
// Initialize the system using the current process [see MSDN for details]
g_process = ::GetCurrentProcess();
g_sym_initialize(g_process, NULL, TRUE);
// Preallocate some memory for loading symbol information.
g_symbol = (SYMBOL_INFO *) ::malloc(sizeof(SYMBOL_INFO) + (MAX_FILENAME_LENGTH * sizeof(char)));
g_symbol->MaxNameLen = MAX_FILENAME_LENGTH;
g_symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
return true;
}
void CallstackSystemDeinit()
{
// cleanup after ourselves
::free(g_symbol);
g_symbol = nullptr;
g_sym_cleanup(g_process);
FreeLibrary(g_debug_help);
g_debug_help = NULL;
}
// Can not be static - called when
// the callstack is freed.
void DestroyCallstack(CallStack *ptr)
{
::free(ptr);
}
CallStack* CreateCallstack(uint8_t skip_frames)
{
// Capture the callstack frames - uses a windows call
void *stack[MAX_DEPTH];
DWORD hash;
// skip_frames: number of frames to skip [starting at the top - so don't return the frames for "CreateCallstack" (+1), plus "skip_frame_" layers.
// max_frames to return
// memory to put this information into.
// out pointer to back trace hash.
uint32_t frames = CaptureStackBackTrace(1 + skip_frames, MAX_DEPTH, stack, &hash);
// create the callstack using an untracked allocation
CallStack *cs = (CallStack*) ::malloc(sizeof(CallStack));
// force call the constructor (new in-place)
cs = new (cs) CallStack();
// copy the frames to our callstack object
unsigned int frame_count = min(MAX_FRAMES_PER_CALLSTACK, frames);
cs->m_frame_count = frame_count;
::memcpy(cs->m_frames, stack, sizeof(void*) * frame_count);
cs->m_hash = hash;
return cs;
}
//------------------------------------------------------------------------
// Fills lines with human readable data for the given callstack
// Fills from top to bottom (top being most recently called, with each next one being the calling function of the previous)
//
// Additional features you can add;
// [ ] If a file exists in yoru src directory, clip the filename
// [ ] Be able to specify a list of function names which will cause this trace to stop.
uint16_t CallstackGetLines(callstack_line_t *line_buffer, const uint16_t max_lines, CallStack *cs)
{
IMAGEHLP_LINE64 line_info;
DWORD line_offset = 0; // Displacement from the beginning of the line
line_info.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
unsigned int count = min(max_lines, cs->m_frame_count);
unsigned int idx = 0;
for (unsigned int i = 0; i < count; ++i) {
callstack_line_t *line = &(line_buffer[idx]);
DWORD64 ptr = (DWORD64)(cs->m_frames[i]);
if (FALSE == g_sym_from_addr(g_process, ptr, 0, g_symbol)) {
continue;
}
strcpy_s(line->function_name, 256, g_symbol->Name);
BOOL bRet = g_sym_get_line_from_addr_64(
GetCurrentProcess(), // Process handle of the current process
ptr, // Address
&line_offset, // Displacement will be stored here by the function
&line_info); // File name / line information will be stored here
if (bRet)
{
line->line = line_info.LineNumber;
strcpy_s(line->file_name, 128, line_info.FileName);
line->offset = line_offset;
}
else {
// no information
line->line = 0;
line->offset = 0;
strcpy_s(line->file_name, 128, "N/A");
}
++idx;
}
return idx;
}
Operators
// Treat as Linked List Node
struct callstack_list
{
CallStack* current_stack = nullptr;
uint16_t total_allocation = 0;
callstack_list* next = nullptr;
};
struct allocation_meta
{
uint16_t size;
callstack_list callstack_node;
};
void* operator new(const size_t size)
{
uint16_t alloc_size = (uint16_t)size + (uint16_t)sizeof(allocation_meta);
allocation_meta *ptr = (allocation_meta*)::malloc((size_t)alloc_size);
ptr->size = (uint16_t)size;
ptr->callstack_node.current_stack = CreateCallstack(0);
ptr->callstack_node.total_allocation = (uint16_t)size;
ptr->callstack_node.next = nullptr;
bool run = true;
callstack_list* currentNode = nullptr;
while (g_callstack_root != nullptr && run)
{
if (currentNode == nullptr)
{
currentNode = g_callstack_root;
}
if (currentNode->next != nullptr)
{
currentNode = currentNode->next;
}
else
{
currentNode->next = &ptr->callstack_node;
run = false;
}
}
if (g_callstack_root == nullptr)
{
g_callstack_root = &ptr->callstack_node;
}
return ptr + 1;
}
void operator delete(void* ptr)
{
if (nullptr == ptr)
return;
allocation_meta *data = (allocation_meta*)ptr;
data--;
if (data->callstack_node.current_stack != nullptr)
DestroyCallstack(data->callstack_node.current_stack);
bool run = true;
callstack_list* currentNode = nullptr;
while (g_callstack_root != nullptr && run && &data->callstack_node != NULL)
{
if (currentNode == nullptr && g_callstack_root != &data->callstack_node)
{
currentNode = g_callstack_root;
}
else
{
g_callstack_root = nullptr;
run = false;
continue;
}
if (currentNode->next != nullptr && currentNode->next != &data->callstack_node)
{
currentNode = currentNode->next;
}
else
{
currentNode->next = nullptr;
run = false;
}
}
::free(data);
}
Test Harness
void ReportVerboseCallStacks(const char* start_time_str = "", const char* end_time_str = "")
{
callstack_list* currentNode = g_callstack_root;
unsigned int totalSimiliarAllocs = 0;
uint32_t totalSimiliarSize = 0;
while (currentNode != nullptr)
{
callstack_list* nextNode = currentNode->next;
uint32_t& currentHash = currentNode->current_stack->m_hash;
uint32_t nextHash;
if (nextNode == nullptr)
nextHash = currentHash + 1;
else
nextHash = nextNode->current_stack->m_hash;
if (nextHash == currentHash)
{
totalSimiliarSize += currentNode->total_allocation;
totalSimiliarAllocs++;
}
if (nextHash != currentHash)
{
//Print total allocs for type and total size
float reportedBytes = convertToReadableBytes(totalSimiliarSize);
std::string size = convertToReadableBytesString(totalSimiliarSize);
char collection_buffer[128];
sprintf_s(collection_buffer, 128, "\nGroup contained %s allocation(s), Total: %0.3f %s\n", std::to_string(totalSimiliarAllocs).c_str(), reportedBytes, size.c_str());
printf(collection_buffer);
//Reset total allocs and size
totalSimiliarAllocs = 0;
totalSimiliarSize = 0;
}
// Printing a call stack, happens when making report
char line_buffer[512];
callstack_line_t lines[128];
unsigned int line_count = CallstackGetLines(lines, 128, currentNode->current_stack);
for (unsigned int i = 0; i < line_count; ++i)
{
// this specific format will make it double click-able in an output window
// taking you to the offending line.
//Print Line For Call Stack
sprintf_s(line_buffer, 512, " %s(%u): %s\n", lines[i].file_name, lines[i].line, lines[i].function_name);
printf(line_buffer);
}
currentNode = currentNode->next;
}
}
void Pop64List(int64_t* arr[], int size)
{
for (int index = 0; index < size; ++index)
{
arr[index] = new int64_t;
*arr[index] = (int64_t)index;
}
}
void Pop8List(int8_t* arr[], int size)
{
for (int index = 0; index < size; ++index)
{
arr[index] = new int8_t;
*arr[index] = (int8_t)index;
}
}
int main()
{
if (!CallstackSystemInit())
return 1;
const int SIZE_64 = 8000;
int64_t* arr_64[SIZE_64];
const int SIZE_8 = 10000;
int8_t* arr_8[SIZE_8];
Pop64List(arr_64, SIZE_64);
Pop8List(arr_8, SIZE_8);
ReportVerboseCallStacks();
CallstackSystemDeinit();
return 0;
}
I finally figured out the answer. In my reporting function I was using std::string to create some of the reporting objects. std::string calls ::new internally to create a small allocation, and then hammers additional memory as the string's internal array reallocates memory. Switching to C-strings solved my problem.

Passing information between SWIG in and freearg typemaps

I have a typemap targetting Python which accepts both an already wrapped pointer object or additionally allows passing a Python sequence. In the case of a wrapped pointer, I do not want to delete the memory as SWIG owns it. However, when processing a sequence I'm allocating a temporary object that needs to be deleted. So I added a flag to my 'in' typemap to mark whether I allocated the pointer target or not. How can I access this flag in the corresponding 'freearg' typemap?
The typemaps look like this:
%typemap(in) name* (void* argp = 0, int res = 0, bool needsDelete = false) {
res = SWIG_ConvertPtr($input, &argp, $descriptor, $disown | 0);
if (SWIG_IsOK(res)) {
$1 = ($ltype)(argp); // already a wrapped pointer, accept
} else {
if (!PySequence_Check($input)) {
SWIG_exception(SWIG_ArgError(res), "Expecting a sequence.");
} else if (PyObject_Length($input) != size) {
SWIG_exception(SWIG_ArgError(res), "Expecting a sequence of length " #size);
} else {
needsDelete = true;
$1 = new name;
for (int i = 0; i < size; ++i) {
PyObject* o = PySequence_GetItem($input, i);
(*$1)[i] = swig::as<type>(o);
Py_DECREF(o);
}
}
}
}
%typemap(freearg) name* {
if ($1 /* && needsDelete */) delete $1;
}
This leads to code being generated that looks like:
{
res2 = SWIG_ConvertPtr(obj1, &argp2, SWIGTYPE_p_MyName_t, 0 | 0);
if (SWIG_IsOK(res2)) {
arg2 = (MyName *)(argp2); // already a wrapper pointer, accept
} else {
if (!PySequence_Check(obj1)) {
SWIG_exception(SWIG_ArgError(res2), "Expecting a sequence.");
} else if (PyObject_Length(obj1) != 3) {
SWIG_exception(SWIG_ArgError(res2), "Expecting a sequence of length ""3");
} else {
needsDelete2 = true;
arg2 = new MyName;
for (int i = 0; i < 3; ++i) {
PyObject* o = PySequence_GetItem(obj1, i);
(*arg2)[i] = swig::as<double>(o);
Py_DECREF(o);
}
}
}
}
if (arg1) (arg1)->someMember = *arg2;
resultobj = SWIG_Py_Void();
{
if (arg2 /* && needsDelete */) delete arg2;
}
According to 11.15 Passing data between typemaps from the SWIG manual:
You just need to use the variable as needsDelete$argnum in the freearg typemap.

passing pointer to function and using realloc

I want to pass a pointer to a function which will call a second function that will use realloc.
The issue is that realloc is returning NULL.
I don't know if the mistake is in the numbers of * in the function call or something else.
Could you please help me ?
The code:
int main(){
// some code.
clause_t* ptr; //clause_t is a structure i declared.
//Some work including the initial allocation of ptr (which is working).
assignLonely(matSAT, ic.nbClause, ic.nbVar, ptr); //the issue is here.
//Some other work
}
void assignLonely(int** matSAT, int nbClause, int nbVar, clause_t* ptr)
{
int i = 0, j = 0;
int cpt = 0;
int indice = -1;
for (i = 0; i < nbClause ; ++i)
{
j = 0;
cpt = 0;
while((j < nbVar) && (cpt < 2))
{
if (matSAT[i][j] != 0)
{
cpt++;
}
else
{
indice = j;
}
if (cpt < 2)
{
deleteClause(indice, &ptr);
}
j++;
}
}
}
void deleteClause(int indiceClause, clause_t** ptr)
{
int i = indiceClause;
int nbElt = sizeof((*ptr))/sizeof((*ptr)[0]);
int tailleElt = sizeof((*ptr)[0]);
while(i+1 < nbElt)
{
(*ptr)[i] = (*ptr)[i+1];
i++;
}
*ptr = (clause_t*)realloc(*ptr, (nbElt-1)*tailleElt);
if (*ptr == NULL)
{
fprintf(stderr, "Erreur reallocation\n");
exit(EXIT_FAILURE);
}
}
You have to declarae function assignLonely similarly to function deleteClause like
void assignLonely(int** matSAT, int nbClause, int nbVar, clause_t** ptr);
if you want that changes of ptr in the function would be stored in the original object in main.
Also take into account that this statement
int nbElt = sizeof((*ptr))/sizeof((*ptr)[0]);
is wrong.
Expression sizeof((*ptr)) will return the size of the pointer. Pointers do not keep information about how many elements in arrays they point to.
So expression
(nbElt-1)
can be equal to zero or even be negative.