Segmentation fault on Ubuntu while running fine on Windows, programmed in c - c

I am writing a small oscillatory motion program that would run on Ubuntu and Windows.
After completing part of the program (major part) I tried to test it on windows, works fine (working with Pelles C)
Then, i copied my data on the Ubunutu computer, Running on a virtual Machine (VMware Workstation).
i compiled it fine using GCC and crashes with "Segmentation fault (core dumped)" error.
Output before crashing:
Simulation Starting...
Creating Containers.....
Done!
Initializing Containers.....
Initializing Container
Done!...
Initializing Container
Done!...
Initializing Container
Segmentation fault (core dumped)
--------------------------------
Part of zDA.c, the function required to initialize vectors before using in simulation
int InitializeArray (DATA *item) {
printf("\nInitializing Container");
item->num_allocated = 0;
item->num_elements = 0;
item->the_array = NULL;
printf("\nDone!...");
if (!item->the_array) {
return -1;
}
return 0;
}
While calling the function, snippet from zSim.c
int Simulate(SIMOPT so,PRINTOPT po) {
printf("\nSimulation Starting...\nCreating Containers...");
//Create Data Objects
//vectors
DATA Theta,Omega,T;
DATA *pTheta = Θ
DATA *pOmega = Ω
DATA *pT = &T;
//Initial Values
int method = so.method;
float g = so.g;
float l = so.l;
float itheta = so.theta;
float iomega = so.omega;
float dt = so.dt;
float df = so.df;
float dw = so.dw;
float q = so.q;
float maxtime = so.maxtime;
//backend variables
float i = 0; //Simulation Counter
int k=0; //Counter to Count array size;
int kmax = 0;
float th,thi,om,omi,t,ti; //Simulation variables
int gt,go,pl,mat;
printf("..");
printf("\nDone!\nInitializing Containers...");
printf("..");
//Initialize Containers
InitializeArray(pTheta);
InitializeArray(pOmega);
InitializeArray(pT); //**FOR SOME REASON, it stops working here -_-
printf("DONE! NIT"); //It worked fine on windows, there are no dependencies.
th = pTheta->the_array[0];
om = pOmega->the_array[0];
t = pT->the_array[0];
i don't get why it worked on windows, didn't on ubuntu, either the compiler on Pelles fixed something for me, or my virtual machine is going crazy,
i mean... it already Initialized 2 out of 3 arrays, what's wrong with the third :)"?

The initialization looks like it would not crash. But the code immediately following it looks suspect. The array has not been initialized (well ... it is initialized, but it is initialized to NULL), yet the following code accesses it:
th = pTheta->the_array[0];

Related

Using a c-program to read an NMEA-string

I am trying to make a c-program that will will a string, but I want it only to read a very small part of it.
The NMEA-telegram that I try to read is $WIXDR, and do receive the necessary strings.
Here's 2 examples of strings that I get into the CPU:
$WIXDR,C,1.9,C,0,H,83.2,P,0,P,1023.9,H,0*46
$WIXDR,V,0.01,M,0,Z,10,s,0,R,0.8,M,0,V,0.0,M,1,Z,0,s,1,R,0.0,M,1,R,89.9,M,2,R,0.0,M,3*60
If it were only 1 string (not both C and V), this would not be a problem for me.
The problem here is that it's 2 seperate strings. One with the temperature, and one with rain-info.
The only thing that I'm interested in is the value "1.9" from
$WIXDR,C,1.9,C,0......
Here's what I have so far:
void ProcessXDR(char* buffPtr)
{
char valueBuff[10];
int result, x;
float OutSideTemp;
USHORT uOutSideTemp;
// char charTemperature, charRain
IODBerr eCode;
//Outside Temperature
result = ReadAsciiVariable(buffPtr, &valueBuff[0], &buffPtr, sizeof(valueBuff));
sscanf(&valueBuff[0],"%f",&OutSideTemp);
OutSideTemp *= 10;
uOutSideTemp = (USHORT)OutSideTemp;
eCode = IODBWrite(ANALOG_IN,REG_COM_XDR,1,&uOutSideTemp,NULL);
}
// XDR ...
if(!strcmp(&nmeaHeader[0],"$WIXDR"))
{
if(PrintoutEnable)printf("XDR\n");
ProcessXDR(buffPtr);
Timer[TIMER_XDR] = 1200; // Update every minute
ComStateXDR = 1;
eCode = IODBWrite(DISCRETE_IN,REG_COM_STATE_XDR,1,&ComStateXDR,NULL);
}
There's more, but this is the main part that I have.
I have found the answer to my own question. The code that would do as I intented is as follows:
What my little code does, is to look for the letter C, and if the C is found, it will take the value after it and put it into "OutSideTemp". The reason I had to look for C is that there is also a similar string received with the letter V (Rain).
If someone have any input in a way it could be better, I don't mind, but this little piece here does what I need it to do.
Here's to example telegrams I receive (I wanted the value 3.0 to be put into "OutSideTemp"):
$WIXDR,C,3.0,C,0,H,59.2,P,0,P,1026.9,H,04F
$WIXDR,V,0.00,M,0,Z,0,s,0,R,0.0,M,0,V,0.0,M,1,Z,0,s,1,R,0.0,M,1,R,89.9,M,2,R,0.0,M,358
void ProcessXDR(char* buffPtr)
{
char valueBuff[10];
int result, x;
float OutSideTemp;
USHORT uOutSideTemp;
// char charTemperature, charRain
IODBerr eCode;
// Look for "C"
result = ReadAsciiVariable(buffPtr, &valueBuff[0], &buffPtr, sizeof(valueBuff));
// sscanf(&valueBuff[0],"%f",&charTemperature);
if (valueBuff[0] == 'C')
//Outside Temperature
result = ReadAsciiVariable(buffPtr, &valueBuff[0], &buffPtr, sizeof(valueBuff));
sscanf(&valueBuff[0],"%f",&OutSideTemp);
OutSideTemp *= 10;
uOutSideTemp = (USHORT)OutSideTemp;
eCode = IODBWrite(ANALOG_IN,REG_COM_XDR,1,&uOutSideTemp,NULL);
}

Segmentation fault printf

When I build rgb lsd_slam
I search about segmentation fault, and I know something about it. But when I debug by stepping through each line, I get the result following:
for (float* pt = data.imageRGB[0]; pt < maxPtRGB; pt++) {
*pt = *rgbImage;
printf("3!\n");
rgbImage++;
}
for(float* pt = data.imageRGB[0]; pt < maxPtRGB; pt++) {
*pt = *rgbImage;
rgbImage++;
}
If you see the two above, the first run without the problem, and the second will show the segmentation fault. I am using Ubuntu 16.04.

Xcode Seemingly Unable to Use Arrays in C

It's very likely that this is user error as I'm somewhat new to Xcode, but I can't figure this out. Hopefully one of you can.
I'm trying to add an array using the following code:
int ArraySum (int MyArray [], int size) {
int sum = 0;
for (int i = 0; i< size; i++) {
sum = sum + MyArray [i];
}
return sum;
}
int main (){
int mynumberarray [6] = {1,2,3,4,5,6};
int the_sum = ArraySum (mynumberarray, 6);
printf ("The Sum is = %d \n", the_sum);
return 0;
}
When I click the build & run button in Xcode, the only output I get is (lldb).
This would typically lead me to believe that I made a mistake somewhere, but when I run the code through Terminal it runs perfectly and gives me the correct sum.
Can anyone help me here? This isn't an isolated incident, I've had several issues working with arrays in Xcode that are working perfectly when executed in Terminal.
Screenshot:
You have breakpoints set in your Xcode project, so the program is pausing at the first breakpoint and giving you the (lldb) debugger prompt. Disable the breakpoints and run and everything should behave as expected. You can either manually disable each breakpoint (by clicking on it - it should then become dimmed), or go to Debug => Disable Breakpoints in the menu bar.

Access violation when trying to populate an array of struct

Original code comment specifying the core question:
The error I am getting is while iterating through the while loop,
memory out of range or something... resizing to 300 ... Access
violation writing location that's the exact Fraze...
I'm trying to implement a faster .Net List<T> equivalent in C.
I'm using blittable data types in C#.
In the code below I've moved a function body to the main function just for testing after I have failed to understand where am I wrong.
The problem seems to be that inside the while loop UntArr does not increment.
What am I doing wrong?
typedef struct {
int Id;
char *StrVal;
}Unit; // a data unit as element of an array
unsigned int startTimer(unsigned int start);
unsigned int stopTimer(unsigned int start);
int main(){
Unit *UntArr= {NULL};
//Unit test[30000];
//decelerations comes first..
char *dummyStringDataObject;
int adummyNum,requestedMasterArrLength,requestedStringSize,MasterDataArrObjectMemorySize,elmsz;
int TestsTotalRounds, TestRoundsCounter,ccountr;
unsigned int start, stop, mar;
//Data Settings (manually for now)
requestedMasterArrLength=300;
requestedStringSize = 15;
//timings
start=0;stop=0;
//data sizes varies (x86/x64) compilation according to fastest results
MasterDataArrObjectMemorySize = sizeof(UntArr);
elmsz= sizeof(UntArr[0]);
TestRoundsCounter=-1;
start = startTimer(start);
while(++TestRoundsCounter<requestedMasterArrLength){
int count;
count=-1;
//allocate memory for the "Master Arr"
UntArr = (Unit *)malloc(sizeof(Unit)*requestedMasterArrLength);
dummyStringDataObject = (char*)malloc(sizeof(char)*requestedStringSize);
dummyStringDataObject = "abcdefgHijkLmNo";
while (++count<requestedMasterArrLength)
{
dummyStringDataObject[requestedStringSize-1]=count+'0';
puts(dummyStringDataObject);
ccountr=-1;
// tried
UntArr[count].Id = count;
UntArr[count].StrVal = (char*)malloc(sizeof(char)*requestedStringSize);
UntArr[count].StrVal = dummyStringDataObject;// as a whole
//while(++ccountr<15)// one by one cause a whole won't work ?
//UntArr[count].StrVal[ccountr] = dummyStringDataObject[ccountr];
}
free(UntArr);free(dummyStringDataObject);
}
stop = startTimer(start);
mar = stop - start;
MasterDataArrObjectMemorySize = sizeof(UntArr)/1024;
printf("Time taken in millisecond: %d ( %d sec)\r\n size: %d kb\r\n", mar,(mar/1000),MasterDataArrObjectMemorySize);
printf("UntArr.StrVal: %s",UntArr[7].StrVal);
getchar();
return 0;
}
unsigned int startTimer(unsigned int start){
start = clock();
return start;
}
unsigned int stopTimer(unsigned int start){
start = clock()-start;
return start;
}
testing the code one by one instead of within a while loop work as expected
//allocate memory for the "Master Arr"
UntArr = (Unit *)malloc(sizeof(Unit)*requestedMasterArrLength);
UntArr[0].Id = 0;
dummyStringDataObject = (char*)malloc(sizeof(char)*requestedStringSize);
dummyStringDataObject = "abcdefgHijkLmNo";
////allocate memory for the string object
UntArr[0].StrVal = (char*)malloc(sizeof(char)*requestedStringSize);
////test string manipulation
adummyNum=5;
UntArr[0].StrVal= dummyStringDataObject;
//
UntArr[0].StrVal[14] = adummyNum+'0';
////test is fine
as it happens and as i am new to pointers i have not realize that when debugging
i will not see the elements of given pointer to an array as i am used to
with normal Array[] but looping through result which i did not even try as when i was hovering above the Array* within the while loop expecting to see the elements as in a normal array:
Data[] DataArr = new Data[1000] <- i have expected to actually see the body of the array while looping and populating the Data* and did not realize it is not an actual array but a pointer to one so you can not see the elements/body.
the solution is via a function now as planed originally :
void dodata(int requestedMasterArrLength,int requestedStringSize){
int ccountr,count;
count=0;
UntArr=NULL;
UntArr = (Unit *)malloc(sizeof(Unit)*requestedMasterArrLength);
while(count!=requestedMasterArrLength)
{
char dummyStringDataObject[]= "abcdefgHi";
UntArr[count].StrVal=NULL;
dummyStringDataObject[requestedStringSize-1] = count+'0';
UntArr[count].Id= count;
ccountr=0;
UntArr[count].StrVal= (char*)malloc(sizeof(char)*requestedStringSize);
while(ccountr!=requestedStringSize){
UntArr[count].StrVal[ccountr] = dummyStringDataObject[ccountr];
++ccountr;
}
++count;
}
}
generaly speaking, x86 compilation would get better performance for this current task , populating an array of a struct.
so i have compiled it also in c++ and c#.
executing similar code in C# and C++
minimum time measured in c# ~ 3,100 ms.
minimum time measured in this code - C ~ 1700 ms.
minimum time measured in C++ ~ 900 ms.
i was surprised to see this last result c++ is the winner but why.
i thought c is closer to the system level, CPU, Memory...

glibc detected when trying to use cvCreateHist in C

This is a part of my code
int histsize=16;
float range=[0,255];
float* ranges[] = { range };
bool uniform=true;
CvHistogram* hist = cvCreateHist(1, &histsize, CV_HIST_ARRAY, ranges, uniform);
But when I try to execute cvCreateHist the program terminates and throws an error saying
* glibc detected malloc(): memory corruption: 0x083109b8 **
I am working in eclipse,Ubuntu.Please help me out.
The truth is that your code shouldn't even compile because of these lines:
float range=[0,255];
bool uniform=true;1
Before answering this question, I must say that I think you can benefit a lot from this post: Writing the perfect question
I don't know what you are trying to do exactly with that code, but the following compiles & doesn't crash:
int histsize = 16;
float range[] = { 0, 255 };
float* ranges[] = { range };
bool uniform = true;
CvHistogram* hist = cvCreateHist(1, &histsize, CV_HIST_ARRAY, ranges, uniform);

Resources