As the title suggests, when I declare structure BasicSetup_S
globally, I get a segmentation fault. But if I move BasicSetup_S
into CallFunction()
the segmentation fault goes away.
The output is correct each time. It produces exactly what I expect to see but I get the segmentation fault. But, if I move the BasicSetup_S
structure inside CallFunction
the segmentation fault goes away. Is there any reason why?
I'm thinking that my entire program may use too much memory causing a fault when I declare more global variables.
For ease of reading, I simplified the names of everything and showed only the useful parts of the code
#include <stdio.h>
#include "stdint.h"
typedef struct BasicSetup
{
uint16_t A;
uint16_t B;
uint16_t C;
uint16_t D;
uint16_t E;
uint16_t F[3];
uint16_t G[7];
}BasicSetup;
BasicSetup BasicSetup_S = {
// A, // B,
1, 2,
// C, // D,
3, 4,
// E, // F[2],[1],[0]
5, 6 , 7 , 8,
// G[6],[5],[4],[3],[2],[1],[0]
9 , 10, 11, 12, 13, 14, 15,
};
void CallFunction(uint8_t *writeBuffer, int begAddress, int endAddress)
{
int i;
uint16_t tempVal;
int StartingPoint = 0;
for (i = begAddress; i < endAddress; i++)
{
// Grabs information from Device Information Structure
if (i >= 0 && i <= 7)
{
// Grab Value
tempVal = *((uint16_t*)&BasicSetup_S.A + i);
// Send Value
writeBuffer[(StartingPoint)++] = tempVal & 0xFF;
}
else if (i >= 13 && i <= 19)
{
// Grab Value
tempVal = *((uint16_t*)&BasicSetup_S.G + i - 13);
// Send Value
writeBuffer[(StartingPoint)++] = tempVal & 0xFF;
}
}
return;
}
int main(int argc, char *argv[]) {
int numOfBytes = 0;
int i = 0;
uint8_t writeBuffer[256];
CallFunction(writeBuffer, 0, 8);
for (i = 0; i < 8; i++) printf("%d, ", writeBuffer[i]);
printf("\n");
CallFunction(writeBuffer, 13, 19);
for (i = 0; i < 6; i++) printf("%d, ", writeBuffer[i]);
printf("\n");
CallFunction(writeBuffer, 19, 20);
for (i = 0; i < 1; i++) printf("%d, ", writeBuffer[i]);
printf("\n");
return 0;
}