Seg Fault:I can't understand why - c

I get a pretty weird segmentation fault error when I am trying to use the same function in two different places.
printTVNode function work fine on main.
On Main:
printTVNode(headTVNode); /* Works fine here */
TVNodePointer headTopic = NULL;
TopicEmmissions(&headTopic,headTVNode,desiredTopic);
When I am trying to use printTVNode inside TopicEmmissions function a get Seg Fault.
void TopicEmmissions(TVNodePointer * headTopic,TVNodePointer headTVNode,char * desiredTopic){
TVNodePointer currentTVNode = headTVNode;
EmmissionPointer currentEmmission;
EventPointer currentEvent;
EventPointer topicSubjects = NULL;
int flag,countEvent = 1,countEmmission = 1;
printTVNode(headTVNode); /* Get Segmentation Fault here*/
...
printTVNode function:
void printTVNode(TVNodePointer headTVNode){
TVNodePointer currentTVNode = headTVNode;
while ( currentTVNode != NULL ){
printEmmission(*(currentTVNode->anEmmission));
currentTVNode = currentTVNode->next;
}
}

The problem seems to be in the following line :
printEmmission(*(currentTVNode->anEmmission));
In a situation where anEmmission is NULL, when you try to dereference it, I think you will get a segfault.
Make sure to check that anEmmission is not NULL before doing dereferencing.

Related

Segmentation fault using IDXGIAdapter

I am reading through the relevant Microsoft docs and found this example of how to create IDGI data struct then use it to read memory size but I get Segmentation fault
#include <iostream>
#include <d3d9.h>
#include <D3D9Types.h>
LPDIRECT3D9 g_pDirect3D = NULL;
LPDIRECT3DDEVICE9 g_pDirect3D_Device = NULL;
int main(void)
{
UINT x = 0; // Ordinal number that denotes the display adapter.
DWORD xWord = 0 ;
D3DADAPTER_IDENTIFIER9 pIdentifier ;
g_pDirect3D = Direct3DCreate9(D3D_SDK_VERSION);
HRESULT hResult = g_pDirect3D->GetAdapterIdentifier(x, xWord, &pIdentifier);
IDXGIDevice * pDXGIDevice;
HRESULT hr = g_pDirect3D->QueryInterface(__uuidof(IDXGIDevice), (void **)&pDXGIDevice);
IDXGIAdapter * pDXGIAdapter;
pDXGIDevice->GetAdapter(&pDXGIAdapter); // segfault at this line
return 0;
}
every thing works perfectly but when I uncomment the line before return 0; I get the error
Microsoft Basic Render Driver
Segmentation fault
why do I get that error
You can't get a IDXGIDevice reference from a IDirect3D9 reference using QueryInterface.
The return HRESULT from the QueryInterface call is probably 0x80004002 (E_NOINTERFACE), so pDXGIDevice is null and the following calls cause a crash. You should always check HRESULT values.
Otherwise, for new developments, you should forget about DirectX9 and use DirectX11 or DirectX12 (and this will enable DXGI).

Segmentation fault - weird debugging with gdb

I'm working in C, Linux terminal. I need to find a pattern in a text and recolor it. GDB debugging can locate the function that is causing the problem via (gdb) backtrace, but it shows me a terrible message when I try to find the exact line:
Error
Program received signal SIGSEGV, Segmentation fault.
strstr_sse2_unaligned ()
at ../sysdeps/x86_64/multiarch/strstr-sse2-unaligned.S:40
40 ../sysdeps/x86_64/multiarch/strstr-sse2-unaligned.S: No such file or dir
ectory.
(gbd)
The broken function is find_and_recolor:
char* my_replace(char *text, char* replacement)
{
int lgreplacement = strlen(replacement);
int lgtext = strlen(text);
char *aux = (char*)malloc((lgreplacement + lgtext + 10) * sizeof(char));
strcpy(aux, replacement);
strcat(aux, text);
return(aux);
}
char* find_and_recolor(char* text, char* pattern)
{
int lgpattern = strlen(pattern);
int lgreplace = lgpattern + 10;//there are exactly 10 characters that must be inserted along the pattern word
int dif = 0;
char *p;
char *replacement = (char*)malloc(lgreplace * sizeof(char));
strcpy(replacement, "\e[0;31m");
strcat(replacement, pattern);
strcat(replacement, "\e[m");//to recolor a word in red, that word must be surrounded by those characters
while(p = strstr(text + dif, pattern))
{
p = my_replace(p, replacement);
p += lgreplace;
dif = p - text;
}
free(replacement);
return strdup(text);
}
it shows me a terrible message when I try to find the exact line:
There is nothing terrible, weird or unusual about this message, you just need to learn proper debugging technique.
What's happening is that the segmentation fault doesn't happen in your code, it happens inside GLIBC code (inside strstr), because you called strstr with bad arguments.
To find which call to strstr that was, use GDB up command to step out of GLIBC code, and into your code. Once you are inside find_and_recolor, you would be able to see the exact line, and print values of text, dif and pattern which caused your crash (assuming you compiled your code for debugging, i.e. with the -g flag).
Updating diff to p-text in while loop where both pointer points to different array doesn't make sense. It is undefined behavior.
Also code has other issues.
Uninitialized variable.
Less optimized as number of call can be reduced.

Why is the segmentation fault showing even after memory allocation?

The code shows the segmentation fault in the function free_nlist()(line#539) within the nlist.c file.
I tried one thing but I do not think that it was logical; I tried allocating the dynamic memory to the variable "nlb_head"(line #542) using the command :
nlb_head = (struct nlblock *) malloc( sizeof( struct nlblock ) );
It did give me the results but can anyone explain as to whether this is correct or not.
void free_nlist( struct nlblock *nlb_head )
{
struct nlblock *nlb_tmp;
nlb_tmp=NULL;
while( nlb_head != NULL )
{
nlb_tmp = nlb_head->next;
free( nlb_head );
nlb_head = nlb_tmp;
}
free(nlb_tmp);
}
The link to the code is given below:
https://drive.google.com/open?id=1BDP-gkSP9rPvAM4oVdNYmwmJqPhy3o_w

Error caused by function that hasn't yet been run

So I'm writing a bill handling system. The data currently sits in a Stack structure that I've written.
I have this partially written function that writes out a report:
void GenerateReport(Bill* bill)
{
PrintBillHeading(bill);
//CallEntry* collatedEntries = CollapseCallStack(bill->callEntries);
//TODO
}
Which works fine as long as I leave the second line commented out. If I uncomment it I get a SIGSEGV fault within the PrintBillHeading() function where indicated below.
void PrintBillHeading(Bill* bill)
{
printf("Big Brother Telecom\n");
printf("Bill Date: %s\n\n",DateTimeToISOString(bill->date));
printf("Contract Holder: %s %s\n", bill->title, bill->name);
printf("Address:\n");
char* addressSeg;
char* addressCpy;
strcpy(addressCpy,bill->address); //This line throws the SIGSEGV
while ((addressSeg = strtok_r(addressCpy,";",&addressCpy)))
{
printf("%s\n\0",addressSeg);
}
}
and for completeness here is my CollapseCallStack() function, this is uncomplete, entirely untested and probably doesn't work.
CallEntry* CollapseCallStack(Stack* calls)
{
int size = calls->topIndex;
CallEntry* collatedSet = malloc(sizeof(CallEntry) * size);
CallEntry* poppedCall;
int curIndex = 0;
while (PopStack(calls,poppedCall))
{
bool found = false;
for (int i = 0; i < size; i++)
{
CallEntry* arrItem = collatedSet + i * sizeof(CallEntry);
if (StringEquals(arrItem->phoneNumber,poppedCall->phoneNumber))
{
found = true;
arrItem->minutes += poppedCall->minutes;
}
}
if (!found)
{
memcpy(collatedSet,poppedCall,sizeof(CallEntry)); //
}
}
}
And the CallEntry struct:
typedef struct{
char* phoneNumber;
int minutes;
DateTime* callDateTime;
} CallEntry;
My question is this: how can a function that hasn't yet been called cause a SIGSEGV fault to be expressed earlier on in a program?
Once I've got past this, I can debug the CollapseCallStack() function myself, although if anyone sees any glaring problems I would appreciate a comment on that.
In function PrintBillHeading(), the statement strcpy(addressCpy,bill->address) uses the value of an uninitialized variable addressCpy. This is undefined behavior. Undefined behavior means that the program may crash in any random place. If the program contains undefined behavior the entire program is invalid.
In addition to the correct answer by AlexP, I'd like to point out another (lurking) undefined behaviour:
void GenerateReport(Bill* bill)
{
PrintBillHeading(bill);
CallEntry* collatedEntries = CollapseCallStack(bill->callEntries);
//TODO
}
Now, CollapseCallStack in your current implementation does not return anything. It will still be called, and actually something will be assigned to your collatedEntries pointer upon your initialization of it.
The problem is that when CollapseCallStack is called, memory for the return value is being allocated, but it never gets assigned a meaningful value, since the return statement is missing. So, essentially your collatedEntries pointer will be initialized with a random garbage value, and if you'd try to dereference it, it would cause UB.

Where should atexit() function go in order to prevent seg fault?

My code works perfectly fine, however when I exit my simpleshell I get a segmentation fault. The final of atexit(final) still gets called and works properly. I think the problem is with the atexit(), because when atexit() is removed from the code I can "exit" (i.e. CNTRL+D) the simpleshell properly. However, restated, once atexit() is inside my code (see below to see where it is), it causes a segmentation fault when I exit (even though "final" executes).
static void final(void) {
flag = 0;
assign6 = fopen(".logfile.txt", "a");
assign62 = fopen(".temp_logger.txt", "r");
while(fgets(test2, sizeof(test2), assign62))
{
fprintf(assign6, test2);
}
fclose(assign6);
fclose(assign62);
remove(".temp_logger.txt");
}
You are not checking the assign62 file pointer for proper fopen and it looks like you are deleting it:
static void final(void) {
flag = 0;
assign6 = fopen(".logfile.txt", "a");
assign62 = fopen(".temp_logger.txt", "r");
if (assign6 && assign62) {
while(fgets(test2, sizeof(test2), assign62))
{
fprintf(assign6, test2);
}
fclose(assign6);
fclose(assign62);
remove(".temp_logger.txt");
}
}

Resources