need help to find segmentation fault error - c

can someone help me to find what cause segmentation fault in my program, I used the gdb but I cannot find which line that cause the error.
Array* Merge(Array *arr1, Array *arr2)
{
int i,j,k;
i=j=k=0;
Array *arr3 = (Array*)malloc(sizeof(Array));
arr3->size = arr1->size + arr2->size;
arr3->length = arr1->length + arr2->length;
while(i<arr1->length && j<arr2->length)
{
if(arr1->A[i] < arr2->A[j])
arr3->A[k++]=arr1->A[i++];
else
arr3->A[k++]=arr2->A[j++];
}
for(;i<arr1->length;i++)
arr3->A[k++]=arr1->A[i];
for(;j<arr2->length;j++)
arr3->A[k++]=arr2->A[j];
return arr3;
}
#include <stdio.h>
#include <stdlib.h>
#include "array1.h"
int main()
{
Array arr,arr1,*arr2;
arr.size=10;
arr.length=5;
arr1.size=10;
arr1.length=5;
arr.A=(int*)malloc(arr.size*sizeof(int));
arr1.A=(int*)malloc(arr.size*sizeof(int));
printf("\n enter elements of arr\n");
for (int i=0;i<arr.length;i++)
scanf("%d",&arr.A[i]);
/**********************************************/
printf("\n enter elements of arr1\n");
for (int i=0;i<arr1.length;i++)
scanf("%d",&arr1.A[i]);
arr2=Merge(&arr, &arr1);
display(*arr2);
return 0;
}
here is the result of the gdb
enter image description here

In Merge you don't allocate any space for arr3's data (probably a member called A looking at the other code)
It would help to see the rest of the code (especially the declaration of Array) but I suspect arr3->A is an uninitialised pointer.

Related

"Invalid Operands to Binary" error when trying to calculate square of elements in array

this code is supposed to read a text file that contains integers, which then finds the squares of these numbers after putting them into an array.
After this its supposed to print the results onto a new text file "result.txt", but I keep getting the error "invalid operands to binary*(have 'int*' and 'int*')" on this line: square[x] = square[x] * square[x];
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int square[100][2];
int x;
int i;
FILE* input=fopen("in.csv","r");
FILE * f=fopen("result.txt","wb");
system("cls");
for(x=0;x<100;x++)
{
fscanf(input,"%d",&square[x][0]);
}
fclose(input);
for(x=0;x<100;x++)
{
square[x] = square[x] * square[x]; //this line produces the error
}
for(i=0;i<100;i++)
{
fprintf(f,"%d -> %d || ",square[i][0],square[i][1]);
}
fclose(f);
getchar();
}
I am using Eclipse IDE and MinGW-w64
I have tried finding solutions online but am stuck, any help or replies would be appreciated, thanks!
square[x] yields an array with two elements. You should reference the [0] and [1] elements like you do in the rest of your code.
square[x][1] = square[x][0] * square[x][0];

Basic Username/Password Code not working in C - Segmentation Fault

I've just started learning C 2 days ago and have tried to write a code that prompts the user to submit a username and password and then cross-references the input with stored data. The idea is that if the inputted username and password match then "Access Granted" would be printed and if not, "Access Denied".
However, I keep receiving "Access Denied.Segmentation fault" whenever I test the code with inputs. Any thoughts on why this would happen? Attaching my code below for reference:
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <cs50.h>
int N;
typedef struct
{
string Username;
string Password;
}
LoginInfo;
int main(void)
{
LoginInfo code[N];
code[0].Username = "Agent X";
code[0].Password = "1314XN";
code[1].Username = "Agent Y";
code[1].Password = "1315YN";
code[2].Username = "Agent Z";
code[2].Password = "1316ZN";
code[3].Username = "Director A";
code[3].Password = "1414AN";
code[4].Username = "VP A";
code[4].Password = "1628VPN";
string User = get_string("Username: ");
string Pass = get_string("Password: ");
for (int i = 0; i < N; i++)
{
if((strcmp(code[i].Username, User) == 0) && (strcmp(code[i].Password, Pass) == 0))
{
printf("Access Granted.\n");
return 0;
}
}
printf("Access Denied.");
return 1;
}
You've defined int N; but didn't initialize it. Since it's at global scope it's given a value of 0.
When you reach the line LoginInfo code[N]; the value of N is still 0 so the array is given a size of 0. Accessing any elements of the array leads to undefined behavior and is the likely source of the fault.
You need to initialize N or otherwise give it a reasonable value before it's used. For example:
int N = 5; // Initialize this!
With this change your code compiles cleanly and runs. Demo on Compiler Explorer
You aren't defining a value for N so if you want N to be 5 change this to
#define N 5
Without a value for N, it is 0 (likely), and so the array is of size 0 and you will always get a segmentation fault.

Function in C only working when an unrelated line is present

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct card_t{
char value;
char suit[50];
} card_t;
card_t draw(){
card_t karta;
int v = (rand() % 13)+2;
int s = (rand() % 4)+1;
if(v<=9){
karta.value = v +'0';
}else{
if (v==10)
karta.value='T';
if (v==11)
karta.value='J';
if (v==12)
karta.value='Q';
if (v==13)
karta.value='K';
if (v==14)
karta.value='A';
}
if (s==1)
strcpy(karta.suit, "of Spades");
if (s==2)
strcpy(karta.suit, "of Hearts");
if (s==3)
strcpy(karta.suit, "of Diamonds");
if (s==4)
strcpy(karta.suit, "of Clubs");
return karta;
}
void face_up(card_t deck[],int size){
for(int i=0;i<=size;i++){
printf("%c %s\n",deck[i].value ,deck[i].suit);
}
}
int main()
{
int size;
card_t *deck;
deck = malloc(100*sizeof(char));
card_t karta;
karta=draw();
for (int i=0; i<100 ; i++){
deck[i]=karta;
if(strcmp(deck[i].suit,"of Spades")==0 && deck[i].value=='A'){
size=i;
break;
}
karta=draw();
/*THIS ONE*/printf("%c %s\n",deck[i].value ,deck[i].suit);
}
face_up(deck,size);
free(deck);
return 0;
}
If I remove the line marked with /THIS ONE/ , the function face_up won't print anything , but if the line is there it works. Any ideas ? Tried it several times and its the same thing .
I would get double print if i leave it there , which i dont need.
Im sorry for the bad code / formatting but i am kinda new to this and yeah ...
Thank you for your help in advance.
This line here deck = malloc(100*sizeof(char)); allocates memory on the heap to store an array of 100 chars. What you want to do, is to allocate an array of 100 card_t. To do this just replace the statement with the following one:
deck = malloc(100*sizeof(card_t));

Segmentation fault on deleting an element after searching it in a heap

The following code deletes an element x from a heap after searching it linearly in the heap
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define MaxSize 100001
struct minheap {
long int a[MaxSize];
int end;
};
void minHeapify(struct minheap *h, int i) {
int largest;
long int temp;
int l=2*i+1;
int r=2*i+2;
largest=i;
if(l<=(h->end) && (h->a[l])<(h->a[i]))
largest=l;
if(r<=(h->end) && (h->a[r])<(h->a[largest]))
largest=r;
if(largest!=i) {
temp=h->a[i];
h->a[i]=h->a[largest];
h->a[largest]=temp;
minHeapify(h,largest);
}
}
int main() {
long int x,i=0,temp=0;
int N;
int type;
scanf("%d",&N);
struct minheap h;
h.end=-1;
while(N--) {
scanf("%d",&type);
if(type==1) {
scanf("%ld",&x);
h.end=h.end+1;
h.a[h.end]=x;
i=h.end;
while(i>0 && h.a[(i-1)/2]>h.a[i]) { //fix minheap on insertion
temp = h.a[(i-1)/2];
h.a[(i-1)/2]=h.a[i];
h.a[i]=temp;
i=(i-1)/2;
}
}
else if(type==2) {
scanf("%ld",&x);
for(i=0;i<=h.end;i++) {
if(x == h.a[i])
break;
}
h.a[i]=h.a[h.end];
h.end=h.end-1;
if(i!=(h.end+1))
minHeapify(&h,i);
}
else if(type==3) {
printf("%ld\n",h.a[0]);
}
}
return 0;
}
But the following test case gives segmentation fault as:
Program terminated with signal SIGSEGV, Segmentation fault.
#0 main () at solution.c:59
59 if(x == h.a[i])
#0 main () at solution.c:59
The entire test case can be found on this link:
https://hr-testcases-us-east-1.s3.amazonaws.com/15379/input04.txt?AWSAccessKeyId=AKIAJ4WZFDFQTZRGO3QA&Expires=1547134261&Signature=D%2B39%2BHr%2F4lRFV%2BetxFwnGWm1iac%3D&response-content-type=text%2Fplain
Why is this segmentation fault occurring?
Given the error message,
> Program terminated with signal SIGSEGV, Segmentation fault.
> #0 main () at solution.c:59 59 if(x == h.a[i])
> #0 main () at solution.c:59
...the value i in the expression: if(x == h.a[i]) is probably out of bounds. This leads to undefined behavior, which in some cases might seem to work, other might lead to a segmentation fault.
Look at this line for a possible the solution:
for(i=0;i<=h.a[h.end];i++)
What is the value of a.end at the time this expression is called?
There is also a potential for problems here:
while(i>0 && h.a[(i-1)/2]>h.a[i])
Where the expression: (i-1)/2 is integer division, and will skip values.
I see a few problems in your code to delete an item:
for(i=0;i<=h.end;i++) {
if(x == h.a[i])
break;
}
h.a[i]=h.a[h.end];
h.end=h.end-1;
if(i!=(h.end+1))
minHeapify(&h,i);
First, if an item with the value you entered is not found, you're going to have trouble because i > h.end. You'll end up either indexing off the end of the array, or deleting the last item.
More importantly, you're not handling the case where the item you replace it with is smaller than the parent. For example, consider this heap:
1
6 2
7 8 3
If you delete the node with value 7, the value 3 replaces it:
1
6 2
3 8
That's not a valid heap. You have to move the 3 up in the heap to create:
1
3 2
6 8
The key here is that if the item you're replacing is in a different subtree than the last item in the heap, it's possible that the replacement node will be smaller than the parent of the replaced node.
So your code has to do this:
h.a[i] = h.a[h.end];
h.end = h.end-1;
// here you have to:
// if (h.a[i] < parentOf(h.a[i]))
// move it up the heap
// else
// minHeapify(&h, i);

Heap Corruption Detected after Normal block (#155) in C

I have a piece of code like this:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
char array[10000];
char *newArray=NULL;
int j=0;
int k;
while(gets_s(array))
{
int length=strlen(array);
newArray=(char *)realloc(NULL,length*sizeof(char));
for(int i=length-1;i>=0;i--)
{
if(array[i]==' '||i==0)
{
if(i==0)
i--;
k=i+1;
while(array[k]!=NULL&&array[k]!=' ')
{
newArray[j++]=array[k++];
}
newArray[j++]=' ';
}
}
newArray[j]='\0';
printf(newArray);
free(newArray);
}
}
What I am trying to do is that I want to reverse the string as I continuously input the string.
For example, I input: "this is a dog", the result will return: "dog a is this", and I want to continue to input another string and found the error:
"HEAP CORRUPTION DETECTED: after Normal block (#155) at 0x004CAF38
CRT detected that the application wrote to memory after end of heap buffer"
What's causing this?
You are not allocating enough memory in your newarray to allot for the end of string terminating character:
newArray=(char *)realloc(NULL,length*sizeof(char));
Later you are setting:
newArray[j]='\0';
where j exceeds the memory size by 1.
Change to:
newArray=(char *)realloc(NULL,length*sizeof(char) + 1);
and
newArray[j-1]='\0'
Also need to reset j.

Resources