C strcmp segmentation fault - c

#include <string.h>
#include<stdio.h>
#include<stdlib.h>
typedef struct bank
{
char an;
char name;
char type;
int bal;
};
int main()
{
int i=0,n;
printf("Enter the number of accounts\n");
scanf("%d",&n);
struct bank a[n];
printf("Enter the details of the users\n");
for(i=0;i<n;i++)
{
scanf("%s%s%s%d",a[i].an,a[i].name,a[i].type,&a[i].bal);
}
printf("The details of the users are\n");
for(i=0;i<n;i++)
{printf("%s\n%s\n%s\n%d\n\n",a[i].an,a[i].name,a[i].type,a[i].bal);}
char atype[10];
printf("Enter the type of account you want to search\n");
scanf("%s",atype);
char typ[10];
char s[]="savings";
char c[]="current";
int result,res1,res2;
result = strcmp(atype,s);
if(result == 0)
{
for(i=0;i<n;i++)
{
typ[10] = a[i].type;
res1 = strcmp(typ,s);
if(res1 == 0)
{
printf("%s\n%s\n%s\n%d\n\n",
a[i].an,a[i].name,a[i].type,a[i].bal);
}
printf("\n");
}
} else
{
for(i=0;i<n;i++)
{
typ[10] = a[i].type;
res2 = strcmp(typ,c);
if(res2 == 0)
{
printf("%s\n%s\n%s\n%d\n\n",
a[i].an,a[i].name,a[i].type,a[i].bal);
}
printf("\n");
}
}
}
so basically ik its my homework but i did everythimg and i still cannot resolve the segmentation fault.please help
i think its something to do with strcmp() function but oh well
i checked all the sources but couldnt really find any fix.
any help would be appreciated.

For starters:
This
typ[10] = ...
accesses typ one past its valid memory. This invokes undefined behaviour, so anything can happen from then on.
In C array indexing is 0-based. So for char[10] the highest allowed index would be 9. Access the 1st element would be done by using 0.

You have made 2 mistakes here .
First your struct bank declaration was wrong. You forgot to declare name an and type as string. You declared it as just character(char).It should be like :-
struct bank
{
char an[100]; // assuming 100 is max size of input strings
char name[100];
char type[100];
int bal;
};
second you cannot do typ[10] = a[i].type; you should use strcpy() Something like this :-
strcpy(typ,a[i].type);
So this corrected code will work :-
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
struct bank // change made 1
{
char an[100];
char name[100];
char type[100];
int bal;
};
int main()
{
int i = 0, n;
printf("Enter the number of accounts\n");
scanf("%d", &n);
struct bank a[n];
printf("Enter the details of the users\n");
for (i = 0; i < n; i++)
{
scanf("%s%s%s%d", a[i].an, a[i].name, a[i].type, &a[i].bal);
}
printf("The details of the users are\n");
for (i = 0; i < n; i++)
{
printf("%s\n%s\n%s\n%d\n\n", a[i].an, a[i].name, a[i].type, a[i].bal);
}
char atype[10];
printf("Enter the type of account you want to search\n");
scanf("%s", atype);
char typ[10];
char s[] = "savings";
char c[] = "current";
int result, res1, res2;
result = strcmp(atype, s);
if (result == 0)
{
for (i = 0; i < n; i++)
{
strcpy(typ,a[i].type); // change made 2
res1 = strcmp(typ, s);
if (res1 == 0)
{
printf("%s\n%s\n%s\n%d\n\n",
a[i].an, a[i].name, a[i].type, a[i].bal);
}
printf("\n");
}
}
else
{
for (i = 0; i < n; i++)
{
strcpy(typ,a[i].type); // change made 3
res2 = strcmp(typ, c);
if (res2 == 0)
{
printf("%s\n%s\n%s\n%d\n\n",
a[i].an, a[i].name, a[i].type, a[i].bal);
}
printf("\n");
}
}
}
So your mistake was not with strcmp()

Related

C - numbers not entering in the "if condition", dont know why

So, basically, I was instructed to make a function that asks the user for a size, and then creates an array with elements chosen by the user...
for example: size:4 , input:10 20 30 40, created array = {10,20,30,40}.
Then next step the user is to apply some function for this created array. Example:
For example, if the user chooses letter 'A' the function "add1" will be applied and all elements of the array will be increased in one unit, so with an input example of {10,20,30,40}, the output will be {11,21,31,41}.
My code is not working, why? Someone can help me? I've used the debugger and the function is not entering in the "if condition".
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int* add1(int* array, int size)
{
int *novo;
novo = malloc(size*sizeof(int));
for (int i = 0; i < size; i++){
*(novo + (i)) = *(array + i)+1;
}
return novo;
};
int* add2(int* array, int size)
{
int *novo;
novo = malloc(size*sizeof(int));
for (int i = 0; i < size; i++){
*(novo + (i)) = *(array + i)+2;
}
return novo;
};
void print1(int* array, int size)
{
for (int i = 0; i < size; i++)
{
printf("%i\n", *(array+i));
}
};
int main(void)
{ int i, elemento, size;
char *new;
printf("Insert Size:\n");
scanf("%i", &size);
int newArray[size];
printf("Insert Elements:\n");
for (i = 0; i < size; i++)
{
scanf("%i", &elemento);
newArray[i] = elemento;
}
printf("Select option:\n");
scanf(" %c", &new);
if (new == 'A') {
int* result;
result = add1(&newArray, size);
print1(result, size);
} else if (new == 'B') {
int* result;
result = add2(&newArray, size);
print1(result, size);
} else if (new == 'C') {
} else if (new == 'D') {
}
}
Change:
char *new;
to
char new;
as
scanf(" %c", &new);
is expecting a character and as the code stands new is an undefined character pointer. So passing a pointer to a undefined pointer is not good.
PLEASE SWITCH ON YOUR COMPILER WARNINGS AND THIS WOULD BE PICKED UP!
new is not a good variable name. As it leads to confusion with C++ keyword
Check the return values for scanf- see the manual page for that
Perhaps using switch instead of if new == 'A' .....

Having a fatal error code - corrupted heap

New picture from an external compiler.. the exit code is ok?
enter image description here
This is the full code. I'm having a trouble program blows away after printing the wanted output to the screen. I guess it's a problem with the way I allocated memory for the array of structs, and the .name field of each struct in a for loop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#define MAX_NAME_LEN 50
typedef struct stud
{
char *name;
int marks[4];
float avg;
}student;
student* Create_Class(int);
void Avg_Mark(student*);
void Print_One(student*);
void printExcellent(student*);
void main()
{
int size, i;
student *arr, *newArr;
printf("\nEnter the number of students: ");
scanf_s("%d", &size);
newArr = Create_Class(&size);
for (i = 0; i < size; i++)
{
printExcellent(newArr+i);
}
for (i=0;i<size;i++) free(newArr[i].name);
free(newArr);
_getch();
}
student* Create_Class(int size)
{
student *p;
char str[MAX_NAME_LEN];
int i, j;
p = (student*)calloc(size , sizeof(student));
if (!p)
{
printf("Memory allocation failure.");
exit(1);
}
for (i = 0; i < size; i++)
{
printf("Enter your name: ");
rewind(stdin);
gets(str);
p[i].name = (char*)calloc(strlen(str)+1,sizeof(char));
if (!(p[i].name))
{
printf("Memory allocation error!");
exit(1);
}
strcpy_s(p[i].name,50,str);
printf("Enter your marks: ");
for (j = 0; j < 4; j++)
{
scanf_s("%d", &p[i].marks[j]);
}
Avg_Mark(p + i);
}
return p;
}
void Avg_Mark(student* s)
{
int i, sum=0;
for (i = 0; i < 4; i++)
sum += s->marks[i];
s->avg = (float)sum / 4;
}
void Print_One(student* s)
{
printf("The average of %s is %.1f\n", s->name, s->avg);
}
void printExcellent(student* s)
{
if ((s->avg) > 85)
Print_One(s);
}
Gonna point out everything fishy I see for you:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#define MAX_NAME_LEN 50
typedef struct stud
{
char *name;
int marks[4];
float avg;
}student;
student* Create_Class(int);
void Avg_Mark(student*);
void Print_One(student*);
void printExcellent(student*);
void main()
{
int size, i;
student *arr, *newArr;
printf("\nEnter the number of students: ");
scanf_s("%d", &size);
// This is wrong. Remove the &...
newArr = Create_Class(&size);
for (i = 0; i < size; i++)
{
printExcellent(newArr+i);
}
for (i=0;i<size;i++) free(newArr[i].name);
free(newArr);
_getch();
}
student* Create_Class(int size)
{
student *p;
char str[MAX_NAME_LEN];
int i, j;
// Consider checking size for a sane value.
// Ok, allocate an array of students.
p = (student*)calloc(size , sizeof(student));
if (!p)
{
printf("Memory allocation failure.");
exit(1);
}
for (i = 0; i < size; i++)
{
printf("Enter your name: ");
// These 2 lines scare the heck out of me. I'd really do this differently.
// gets is the devil and the see:
// https://stackoverflow.com/questions/20052657/reversing-stdin-in-c
// for why this may not work well.
rewind(stdin);
gets(str);
// What if str is not a terminated string? Then 1 char of 0? Guess this is ok. Hope it doesn't overflow on the copy below though (consider fixed max size and not using a temporary)
p[i].name = (char*)calloc(strlen(str)+1,sizeof(char));
if (!(p[i].name))
{
printf("Memory allocation error!");
exit(1);
}
// Do a fast copy of up to 50 chars. I'd really want to verify this output to be sure it works.
strcpy_s(p[i].name,50,str);
printf("Enter your marks: ");
for (j = 0; j < 4; j++)
{
// Hope this inputs the way you want.
scanf_s("%d", &p[i].marks[j]);
}
// This should work, but I prefer more explicit pointers.
Avg_Mark(p + i);
}
return p;
}
void Avg_Mark(student* s)
{
// What if s is Null?
int i, sum=0;
// 4 is a magic number. Make this a constant.
for (i = 0; i < 4; i++)
sum += s->marks[i];
// This won't be as accurate as you want. Consider an integer solution.
s->avg = (float)sum / 4;
}
void Print_One(student* s)
{
// What if s is Null? What about s->name?
printf("The average of %s is %.1f\n", s->name, s->avg);
}
void printExcellent(student* s)
{
// What if s is Null?
if ((s->avg) > 85)
Print_One(s);
}
Note: While going through this code, I did not see any "red flags" except for the & on the size and perhaps the gets/rewind calls. I'd still add null asserts to your functions and also walk through it with a debugger to be sure that everything is as you expect. Honestly, there is enough going on here that I'd prefer the debugger help to my quick trace of the code while I was writing comments.
Update
If I change all your scanf_s to scanf() calls, replace your gets() / rewind() calls to a simple scanf("%s", str) call, and change your funky strcpy_s() function to a simpler strcpy() or strncpy() call, your program does not seem to crash for me. My money is that the strcpy_s() call is corrupting RAM while doing its "fast" copy.

How to search for names by letters in a string Array?

Do anybody knows how to search for a name in a string array? If i register the name 'jacob' and search for cob I need to get jacob shown instead of not showing up anything. I don't know if strcmp is the right way to do it. Any ideas?
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX 20
struct name{
char name[MAX];
};
void getRegister(struct name name[], int *nrNames);
void getSearch(struct name name[], int nrNames);
int readLine(char s[], int length);
int main(){
int run=1;
struct name name[MAX];
int nrNames=0;
while(run){
char choice;
printf("\n (1)Register\n(2)Search\n(3)Quit\n");
scanf(" %c%*c", &choice);
if(choice=='1') getRegister(name, &nrNames);
if(choice=='2') getSearch(name, nrNames);
if(choice=='3') run=0;
}
return 0;
}
void getRegister(struct name name[], int *nrNames){
char input[MAX];
printf("Enter name: ");
readLine(input, MAX);
(*nrNames)++;
}
void getSearch(struct name name[], int nrNames){
int i;
char input[MAX];
printf("Enter name: ");
readLine(input, MAX);
if(i>=0){
printf("Name/s:\n");
for(i=0; i<nrNames;i++){
if(strcmp(input, name[i].name)==0){
printf("\n%s\n",name[i].name);
}
}
}
}
int readLine(char s[], int length){
int ch, i=0;
while(isspace(ch=getchar()));
while(ch!='\n' && ch!=EOF) {
if(i<length) s[i++]=ch;
ch = getchar();
}
s[i]='\0';
return i;
}
Try to search for the match in the array. The code below displays a position for each occurrence of the second array in the first array. It uses naive approach. There are more efficient algorithms like Knuth-Morris-Pratt or Boyer-Moore algorithm.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX 20
int main(){
char c;
char name[MAX], search_name[MAX];
int i = 0, j = 0, match = 0, count = 0;
printf("Register name: ");
while ((c = fgetc(stdin)) != '\n') {
if (i < MAX){
name[i++] = c;
}
}
name[i] = '\0';
printf("Search name: ");
i = 0;
while ((c = fgetc(stdin)) != '\n') {
if (i < MAX){
search_name[i++] = c;
}
}
search_name[i] = '\0';
i=-1;
match = 0;
do {
i++;
j = 0;
do {
if (name[i+j] == search_name[j])
match = 1;
else {
match = 0;
break;
}
j++;
} while (search_name[j] != '\0');
if (match)
printf("Match on position %d ", i);
} while (name[i+j] != '\0');
printf("\n");
return 0;
}
I found the soulution myself. Here is the code for those who get stuck as I did.
void searchName(const struct varor reg[], int nrOfGoods){
int i;
char name[20];
printf("Enter name: ");
readLine(name, WORDLENGTH);//gets input
if(i>=0){
printf("\nId.number \t Name \t\t\t Quantity\n");
for(i=0; i<nrOfGoods;i++){
if(strstr(reg[i].name, name)!=NULL){ //this should do the job
printf("%-17d%-24s%-5d\n",reg[i].idnumber,reg[i].name.reg[i].quantity);
}
}
}
}

Dynamic array of Structs, delet elements

I am trying to create a database program of students where you should be able to add/modify and delete students. I have managed to get the add function working, and also the modify function but the delete function gives me some problems. my code seems to crash when im trying to delete a student from the database, can anyone tell me where the problem lies?
Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* TODO: Avoid global variables. */
struct student {
char name[60];
long long personalNumber;
char gender[6];
char studyProgram[60];
char email[30];
int age;
};
struct student *pointer = NULL;
int numberofstudents = 0;
void modify()
{
long long persnr;
long long comp;
int match = 0;
printf("Please enter the personal number that you wish to modify: \n");
scanf("%lld", &persnr);
getchar();
for(int i = 0; i <= numberofstudents; i++)
{
comp = ((pointer+i)->personalNumber);
printf("%lld\n", ((pointer+i)->personalNumber));
printf("%lld\n", comp);
printf("Inne");
if (pointer[i].personalNumber == persnr && match == 0)
{
printf("Enter name, personalnumber, gender, studyprogram, email and age in this order\n");
scanf("%s%lld%s%s%s%d", (pointer+i)->name, &(pointer+i)->personalNumber, (pointer+i)->gender, (pointer+i)->studyProgram, (pointer+i)->email, &(pointer+i)->age);
match = 1;
getchar();
}
if (match == 0)
{
printf("Could not find person");
}
}
}
void deletestudent()
{
long long persnr;
long long comp;
int match = 0;
printf("Please enter the personal number that you wish to delete: \n");
scanf("%lld", &persnr);
getchar();
struct student *temporary = malloc((numberofstudents - 1) * sizeof(struct student));
for(int i = 0; i <= numberofstudents; i++)
{
if (pointer[i].personalNumber == persnr && match == 0)
{
match = 1;
}
else if (match == 1){
temporary[i-1] = pointer[i];
}
else
{
temporary[i] = pointer[i];
}
if (match == 0)
{
printf("Could not find person");
}
}
free(pointer);
pointer = temporary;
}
void add(){
if (numberofstudents > 0)
{
pointer = (struct student*) realloc(pointer, (numberofstudents+1) * sizeof(struct student));
printf("Lyckades allokeringen!\n\n");
}
printf("Enter name, personalnumber, gender, studyprogram, email and age in this order\n");
scanf("%s%lld%s%s%s%d", (pointer+numberofstudents)->name, &(pointer+numberofstudents)->personalNumber, (pointer+numberofstudents)->gender, (pointer+numberofstudents)->studyProgram, (pointer+numberofstudents)->email, &(pointer+numberofstudents)->age);
getchar();
printf("Visar data:\n");
for(int i = 0; i <= numberofstudents; ++i)
{
printf("%s\t%lld\t%s\t%s\t%s\t%d\n", (pointer+i)->name, (pointer+i)->personalNumber, (pointer+i)->gender, (pointer+i)->studyProgram, (pointer+i)->email, (pointer+i)->age);
}
numberofstudents = numberofstudents+1;
}
int main(void)
{
pointer = (struct student*) malloc(2 * sizeof(struct student));
if (pointer == NULL)
{
printf("pointer NULL");
exit(1);
}
int run = 1;
int choice;
while (run == 1)
{
printf("Please enter an option listed below\n1.ADD\n2.Modify\n3.Delete\n4.Search\n5.Save\n6.Load\n7.Exit");
scanf("%d", &choice);
getchar();
switch(choice) {
case 1 :
add();
break;
case 2 :
modify();
break;
case 3 :
deletestudent();
case 7 :
exit(0);
break;
default :
break;
}
}
return 0;
}
As mentioned in a comment, this:
for(int i = 0; i <= numberofstudents; i++)
is a huge warning sign. In C, such a loop should typically have i < numberofstudents in it, assuming numberofstudents is the actual length of the array.
Using <= rather than < makes the loop go one step too far, thus indexing outside the array and causing undefined behavior.
Writing outside heap-allocated memory and then trying to free() it is a good way to provoke crashes, since there's a chance you're stepping on the heap allocator's data structures (in practice; in theory all that happens is that you get undefined behavior and thus anything can happen).

conflicting types for allocArray

guys I'm trying to compile my program in c but I'm getting this error (conflicting types for allocArray)?
Here is my code:
#include <stdio.h>
#include <stdlib.h>
int number(int);
char *allocArray(int);
int main ()
{
printf("Enter a number: ");
int userNumber;
scanf("%d", &userNumber);
int m= number(userNumber);
printf("\nThe number is %d", m);
printf("\n");
printf("*****************************************************\n");
printf("The array is %s", alloArray(5));
}
int number(int n)
{
int num = n;
return num;
}
char *alloArray(int num)
{
char *addr;
addr = (char *) malloc(num);
//addr = char[num];
return addr;
}
You've misspelt allocArray as alloArray (twice, in fact).

Resources