I have an array of structs, each of which describes what I would call a signal. I declared my struct this way :
/* Structure for keywords */
struct varStruct
{
char* varName;
int varOccurence;
} signals[MAX_SIGNALS];
I’m working in a loop which analyze a file and dynamically find the signal declarations, called newArrayName in my case. What I would like to do, is to add the read signal to the array ONLY IF it’s not already contained. Otherwise, I should increment the varOccurence variable.
Here is my code, but I have a segmentation fault (so no further information)…
// We are in the loop that get the signals sequentially
char* newArrayName = TheValueOfTheReadSignal.
int i;
// We browse all the array...
for(i=0; i < MAX_SIGNALS; i++)
{
// If a signal already has the name of the currently-read signal, we inc its occurence
if(strcmp(signals[i].varName, newArrayName) == 0)
{
signals[i].varOccurence++;
}
// Otherwise, we add a new signal with the read-name and an occurence corresponding to the value of a static variable that's incremented after each signal-reading.
else
{
signals[index_Array].varName = newArrayName;
signals[index_Array].varOccurence = index_Array;
}
}
// We increment index_Array, which is a static int variable
index_Array ++;
// End of the loop that gets the signals
Which leads to a segmentation fault. I’m not very good in C language, I would even say I am very bad at it. My guess here is that the signal array has not been initialized, so signal[i] doesn’t have any sense for him, but I don’t know how to initialize an array of structs. Maybe it’s another reason, I don’t know.
Thank you very much for your help.
While you have no entries in recorded
signals, or wheniis larger than the number of recorded entries minus one,, thestrcmp(signals[i].varName, newArrayName)tries to dereference the invalid (uninitialised orNULL) pointersignals[i].varName.Beyond that, as soon as
index_Arraybecomes as large asMAX_SIGNALS(or larger),you write past the end of the array, which is undefined behaviour and will likely cause memory corruption and/or a segmentation fault – directly, or as a consequence of the memory corruption.
In your loop, you write to
signals[index_Array]every time you find a signal with a different name, and you incrementindex_Arrayeach time after the loop is run, regardless of whether you already have some signal with that name or not. You should check whether you already have recorded the signal, and only if not write the new entry and incrementindex_Array: