I have a 10k lines of code C program that sometimes crashes.
I cannot replicate that crash. All I can do is to wait for it to happen and then try to debug it.
This is what I get from drmingw
EXCEPTION PID=18632 TID=10612 ExceptionCode=0xc0000005 dwFirstChance=0
mypgr.exe caused an Access Violation at location 0000000000402CB2 in
module mypgr.exe Reading from location 0000000000000000.
AddrPC Params
0000000000402CB2 0000000000A862D0 0000000000000003 00000000035BE380 mypgr.exe!manage_ids [C:/Users/mn/Documents/code blocks/zbr/common.c # 440]
if(unique_id[i]->idd[32] != 0)
log_errors_to_file("xd2");
dbg_str_len = 0;
for(int xd = 0;xd < 32;xd++) { // ERROR IN THIS LOOP
if(ant_tb[j][k]->idd[xd] == 0)
break;
dbg_str_len++;
};
if(dbg_str_len != 32)
log_errors_to_file("xd3");
if(ant_tb[j][k]->idd[32] != 0)
log_errors_to_file("xd4");
I know this code does not make any sense but I tried many strange things to replicate the crash.
Anyway my debugger shows that below line is causing the problem
for(int xd = 0;xd < 32;xd++){if(ant_tb[j][k]->idd[xd] == 0) break;dbg_str_len++;};
But why? Is it possible to crash the app by just reading?
Related
Upon calling addrtab = g_hash_table_new_full(g_int_hash, g_int_equal, g_free, NULL); the execution aborts and the following is reported: GLib-ERROR **: 15:23:58.535: ../../../glib/gmem.c:138: failed to allocate 11755944670652 bytes. What puzzles me is the amount of memory requested.
Now a bit of details: I'm writing in C using glib-2.66 on Ubuntu 20.04. Commenting out the previously reported line solves the error entirely. g_hash_table_new_full() is used elsewhere in the program without causing any error.
For completeness I'm posting the function that calls that g_hash_table_new_full()
void addr_advertise (hash_node_t* alice, hash_node_t* bob){
GHashTable* addrtab = NULL;
if ((alice->data->key != bob->data->key) && !(alice->data->attackerid == 1 && bob->data->attackerid == 1)) {
addrtab = g_hash_table_new_full(g_int_hash, g_int_equal, g_free, NULL);
if(alice->data->attackerid == -1){
//populate_honest_addr_table(addrtab, alice->data->known_peers);
}
else{
//add_malicious_to_table(addrtab);
}
execute_addr(simclock + FLIGHT_TIME, alice, bob, 5, simclock, alice->data->key, addrtab);
}
}
addr_advertise itself is called multiple times before causing the error.
As reported in gmem.c the error is caused by a g_malloc0() (line 138) that requests too much memory. How is it possible that g_malloc asks for so many bytes? Why previous executions of the same function work perfectly and most of all what could be the origin of the error?
img of error
Above is an error I have been getting, in relation to this line in my program:
storedData[k] = min(dist[index1][k],dist[index2][k]);
Now here is the surrounding functions to this line:
for(int k = 0; k <arraySize; k++){
if(k!= index1 && k != index2){
if(method == SINGLE_LINKAGE){
storedData[k] = min(dist[index1][k],dist[index2][k]);
} else {
storedData[k] = max(dist[index1][k],dist[index2][k]);
}
}
}
Now after playing around with it for quite a while, I realised that the issue it has is with the incrementing 'k' variable in the for loop. More specifically it is worried that when used as an index in dist, the value returned will be uninitialised. Now in terms of functionality, my program works fine and does everything I want it to do. More notably, I have also initialised this function elsewhere in a helper function which is why this confuses me more. I have initialised all the values from index 0-arraysize which in my head means this should never be an issue. Im not sure if maybe this is caused because its done outside of the main function or something. Regardless it keeps giving me grief and I would like to fix it.
You need to work back from the error to its origin. Even if you are initializing your arrays, it is possible that something is 'uninitializing' them again afterwards. memcheck does not flag uninitialized data when it is copied, only when it affects the outcome.
So in pseudo-code you might have
Array arr;
Scalar uninit; // never initialized
init_array(arr);
// do some stuff
arr[3] = uninit; // no error here
for (i = 1 to arr.size)
store[i] = max(arr[i], arr[i-1]; // errors for i == 3 and 4
There are two things that you could try. Firstly, try some 'printf' debugging, something like
for(int k = 0; k <arraySize; k++) {
if(k!= index1 && k != index2) {
fprintf(stderr, "DEBUG: k %d index1 %d index2 %d\n", k, index1, index2);
// as before
Then run Valgrind without a log file. You should then be able to see which indices cause the error(s).
Next, try using ggbserver. Run valgrind in one terminal with
valgrind --vgdb-error=0 prog args
and then run gdb in a second terminal to attach (see the text that is output in the 1st terminal for the commands to use).
You can then use gdb as usual (except no 'run') to control your guest app, with the additional ability to run valgrind monitor commands.
I have a piece of code in which malloc() makes the program pause, without neither really crashing, nor returning an error code (NULL).
Piece of code (has to be executed 24 times, stops at the 22th) :
fprintf(stderr, "malloc");
//-- copy sound
pitched_sound = malloc(sizeof(Mix_Chunk));
if (pitched_sound == NULL)
return -1;
*pitched_sound = *orig_sound;
pitched_sound->abuf = malloc(sound->alen / note_factor);
if (pitched_sound->abuf == NULL)
return -1;
fprintf(stderr, "mallocok.");
Any idea?
I'm running on a Rasperry Pi (ARM), could be related?
How could I debug this?
Many thanks!
I am having a problem with a segmentation fault working in C, and I cannot figure out why this is occurring. I think it has something to do with misuse of the fget(c) function.
while((ch = fgetc(fp))!= EOF) {
printf("Got inside first while: character is currently %c \n",ch); //**********DELETE
while(ch != '\n') {
char word[16]; //Clear out word before beginning
i = i+1; //Keeps track of the current run thru of the loop so we know what input we're looking at.
while(ch != ' ') {
printf("%c ",ch); //**********DELETE
//The following block builds up a character array from the current "word" (separated by spaces) in the input file.
int len = strlen(word);
word[len] = ch;
word[len+1] = '\0';
printf("%s",word);
ch = fgetc(fp);
}
//The following if-else block sets the variables TextA, TextB, and TextC to the appropriate Supply Types from the input.
//This part may be confusing to read mentally, but not to trace. All it does is logically set TextA, B, and C to the 3 different possible values SupplyType.
if(word!=TextB && word!=TextC && i==1 && TextB!="") {
strcpy(TextA,word);
}
else if(word!=TextA && word!=TextC && i==1 && TextC!="") {
strcpy(TextB,word);
}
else if(word!=TextB && word!=TextA && i==1) {
strcpy(TextC,word);
}
switch(i) {
case 1:
if(TextA == word) {
SubTypeOption = 1;
}
else if(TextB == word) {
SubTypeOption = 2;
}
else if(TextC == word) {
SubTypeOption = 3;
}
break;
case 2:
//We actually ultimately don't need to keep track of the product's name, so we do nothing for case i=2. Included for readibility.
break;
case 3:
WholesalePrice = atof(word);
break;
case 4:
WholesaleAmount = atoi(word);
break;
case 5:
RetailPrice = atof(word);
break;
case 6:
RetailAmount = atoi(word);
break;
}//End switch(i)
ch = fgetc(fp);
}//End while(ch != '\n')
//The following if-else block "tallys up" the total amounts of SubTypes bought and sold by the owner.
if(SubTypeOption == 1) {
SubType1OwnersCost = SubType1OwnersCost + (WholesalePrice*(float)WholesaleAmount);
SubType1ConsumersCost = SubType1ConsumersCost + (RetailPrice *(float)RetailAmount);
}
else if(SubTypeOption == 2) {
SubType2OwnersCost = SubType2OwnersCost + (WholesalePrice*(float)WholesaleAmount);
SubType2ConsumersCost = SubType2ConsumersCost + (RetailPrice *(float)RetailAmount);
}
else if(SubTypeOption == 3) {
SubType3OwnersCost = SubType3OwnersCost + (WholesalePrice*(float)WholesaleAmount);
SubType3ConsumersCost = SubType3ConsumersCost + (RetailPrice *(float)RetailAmount);
}
}//End while((ch = fgetc(fp))!= EOF)
Using gdb (just a simple run of the a.out) I found that the problem is related to getc, but it does not tell which line/which one. However, my program does output "Got in side the first while: character is currently S". This S is the first letter in my input file, so I know it is working somewhat how it should, but then causes a seg fault.
Does anyone have any advice on what could be going wrong, or how to debug this problem? I am relatively new to C and confused mostly on syntax. I have a feeling I've done some small syntactical thing wrong.
By the way, this snippet of the code is meant to get a word from a string. Example:
Help me with this program please
should give word equaling "Help"
Update: Now guys I am getting kind of a cool error (although cryptic). When I recompiled I got something like this:
word is now w S
word is now w Su
word is now w Sup
... etc except it goes on for a while, building a pyramid of word.
with my input file having only the string "SupplyTypeA 1.23 1 1.65 1" in it.
UPDATE: Segmentation fault was fixed (the issue was, I was going past the end of the file using fgetc() ). Thanks everyone.
If anyone still glances at this, could they help me figure out why my output file does not contain any of the correct numbers it should? I think I am probably misusing atof and atoi on the words I'm getting.
Make sure you compile the program with -g -O0 options
Next step through the program line by line in GDB, watch and understand what your program is doing. Look at the various variables. This is the essential debugging skill.
WHen it dies type the command 'k' this will give you a stack trace the last line of the trace will have the failing line number, but you know that anyway because you were on the line shen you did a step command
There is no "fget" in good old C, but maybe you're using a more modern version that has something named "fget". Most likely, you meant to use "fgetc". When a C I/O function starts with "f", it usually wants a FILE* handle as an argument, as "fgetc" does. Try using "fgetc" instead, after reading the documentation for it.
I am working in an assignment and am experiencing some weird stuff. I have this while loop in my program that does not seem to branch into the for loop. I have placed two print statements and only the "1" prints over and over again. Note that this only happens when I compile and run from the linux terminal. Now what seem weird is that if i run the exact same code (while loop plus everything else) in Netbeans it seems to compile and behave as expected. Anyone know what might be wrong. Here is the code. I appreciate your help.
while(strstr(p,string_a)!= NULL)
{
p = trailerp + pholderp;
long int index = strstr(p,string_a) - (p+1); // -1 where it hits
printf("1");
for( i = 0; i <= index; i++)
{
printf("2");
p2[trailerp2] = pholderp[trailerp];
trailerp++;
trailerp2++;
if(i == index)
{
int j;
for(j=0; j <= lenb-1; j++) // insert the new string
{
p2[trailerp2] = string_b[j];
trailerp2++;
}
trailerp++;
}
}
}
Edit: I have found the problem. Netbeans seems to be broken in this OS.
This is because strstr(p,string_a) returns either p or 0 in this part:
long int index = strstr(p,string_a) - (p+1); // -1 where it hits
which results in index < 0 and prevents going into the loop.
You must print both p and string_a immediately before this statement to see what is going wrong there.