C- Segmentation fault (core dumped) - c

I am constantly getting "Segmentation fault (Core dumped)" error in the following c program. Please help me debug the program.
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
int numcmp(const char *a,const char *b){
if(atoi(a)==atoi(b)) return 0;
return -1;
}
int isequal(char *a,char *b,int (*cmp)(const char *,const char *)){
if(!cmp(a,b)) return 1;
return 0;
}
int main(int argc,char *argv[]){
if(argc!=3){
puts("Usage: Compare two string alphabeticaly or numericaly");
printf("Syntax: %s string1 string2\n",argv[0]);
exit(-1);
}
if(isequal(argv[1],argv[2],isalpha(argv[1])?strcmp:numcmp))
printf("%s and %s are equal\n",argv[1],argv[2]);
else
printf("%s and %s are not equal\n",argv[1],argv[2]);
}

isalpha only works for chars, not whole strings. You could write a function for that:
/* 1 - only letters, 0 - other characters */
int str_isalpha(const char* str) {
while (*str)
if (!isalpha(*(str++)))
return 0;
return 1;
}
and then use it appropriately. But actually, I don't see a reason for using numcmp here at all. Comparing ints and const char*s should yield the similar results.

Related

Segmentation fault (core dumped) error when running my program

so i am supposed to create a program that analyzes said text file and when i first ran it, i didn't have the text file created, but once i created it and tried to run the program i got a seg fault error and now i don't know how to fix it.
#include <stdio.h>
#include <string.h>
#define FILENAME "poems.txt"
int getWords(int maxWord, char words[][maxWord], FILE*);
int countLetters(char str_letter[]);
int countLowerCase(char str_lower[]);
int countVowels(char str_vowel[]);
int main()
{
int maxWord=50;
int numWord=0;
char words[numWord][maxWord];
char str_letter[75];
char str_lower[75];
char str_vowel[75];
FILE* fp;
int numLetter;
int numLower;
int numVowel;
fp=fopen(FILENAME, "r");
if(fp==NULL) {
printf ("poems.txt could not be found!\n");
}
else {
getWords(maxWord, words, fp);
countLetters(str_letter);
countLowerCase(str_lower);
countVowels(str_vowel);
printf ("There are %d letters in your file.\n", numLetter);
printf ("There are %d lower case letters in your file.\n", numLower);
printf ("There are %d vowels in your file.\n", numVowel);
fclose(fp);
}
return 0;
}
int getWords(int maxWord, char words[][maxWord], FILE* inFILE)
{
int numWord=0;
char poem;
while(fscanf(inFILE, "%s", &poem)==1){
words[numWord][maxWord]=poem;
numWord++;
}
numWord++;
return numWord;
}
int countLetters(char str_letter[])
{
int numLetter=0;
for(int i=0; i<strlen(str_letter); i++) {
if((str_letter[i]>'a' && str_letter[i]<'z')||(str_letter[i]>'A' && str_letter[i]<'Z'));
numLetter++;
}
return numLetter;
}
int countLowerCase(char str_lower[])
{
int numLower=0;
for(int i=0; i<strlen(str_lower); i++) {
if(str_lower[i]>'a' && str_lower[i]<'z');
numLower++;
}
return numLower;
}
int countVowels(char str_vowel[])
{
int numVowel=0;
for(int i=0; i<strlen(str_vowel); i++) {
if(str_vowel[i]=='a'||str_vowel[i]=='e'||str_vowel[i]=='i'||str_vowel[i]=='o'||str_vowel[i]=='u')
{
numVowel++;
}
else if(str_vowel[i]=='A'||str_vowel[i]=='E'||str_vowel[i]=='I'||str_vowel[i]=='O'||str_vowel[i]=='U')
{
numVowel++;
}
}
return numVowel;
}
You are making so many mistakes on your code, so i need to ask, you understands how dynamic memory allocation and pointers works in C? Is not like other languajes, you need to allocate memory before you access to them.
If you dont have a text file, your code works and the output is:
poems.txt could not be found!
So up to here everithings seems to work fine, but it doesn't.
Lets go to the line where you declare:
int maxWord=50;
int numWord=0;
char words[numWord][maxWord];
Here you are saying "SAVE ME AN ARRAY OF 0 POSITIONS AS COLUMNS AND 50 POSITIONS OF ROWS" so when you execute the following code in the function getWords, your code breaks.
while(fscanf(inFILE, "%s", &poem)==1){
words[numWord][maxWord]=poem;
numWord++;
}
Because the position:
words[1][maxWord]
isn't allocated.
You got two ways of allocate memory in C as far as i know, dynamic and static memory allocation.
I believe you came from learning another languaje like python or javascript where this types of things "works" but not in C.
If you want to solve this problems take a look to dynamic memory allocation and how C pointers works, you can make your code unstopable!

Why is Segmentation fault when using GMP?

I am using the GMP. My program can build successfully, But run failed. The following is error things:
a=1231231231231231
res^n != a
Segment fault
All codes in my program is:
#include <gmp.h>
#include <stdio.h>
int main()
{
mpz_t a,res;
unsigned long int n = 123;
char str1[] = "1231231231231231";
mpz_init_set_str(a, str1, 10);
gmp_printf("a=%Zd\n",a);
mpz_init(res);
if(mpz_root(res, a, n)){
printf("res^n == a\n");
}
else{
printf("res^n != a\n");
}
mpz_clears(a,res);
return 0;
}
You have to call mpz_clears() like:
mpz_clears(a,res, NULL);
Here's what the documentation says:
Function: void mpz_clears (mpz_t x, ...)
Free the space occupied by a NULL-terminated list of mpz_t variables.

Reallocating char** array in c (Seg fault core dumped)

I m reallocating a char** array with every entry and while compiling comes back clean, only the first entry is stored and I get Segmentation fault (core dumped) always when i try to register a 4th entry.
Here is the relevant code in main.c:
int main(int argc, char *argv[])
{
int i,sizea,sizeb,choice,letters,check,mistakes,count;
char C[26][2];
char **A,**B,a;
A=(char**)malloc(sizeof(char*));
*A=(char*)malloc((MAX_CHAR+1)*sizeof(char));
sizea=1;
build(&A,&sizea);
return 0;
}
And here is the implementation of the method in mylib.c:
void build(char ***A, int *sizea)
{
*A=(char**)realloc(*A,(*sizea) * sizeof(char*));
*A[*sizea-1]=(char*)malloc((MAX_CHAR+1)*sizeof(char));
printf("Give word :");
scanf("%s",(*A[*sizea-1]));
(*sizea)++;
}
Thanks a lot for your help.
edit: similar problems in this method that werent fixed by doing the same thing
void find(char **A, char ***B, int letters,int sizea, int *sizeb){
int i,j,k,dummy;
char a='a';
for(i=0;i<(sizea-1);i++){
printf("here\n");
if(A[i][letters]=='\0'){
*B=(char**)realloc(*B,(*sizeb+1) * sizeof(char*));
(*B)[*sizeb]=(char*)malloc((letters+1)*sizeof(char));
(*B)[*sizeb-1]=A[i];
*sizeb++;
printf("%s\n", (*B)[i]);
}
}
}
The problem is here:
scanf("%s",(*A[*sizea-1]));
The array index operator [] has higher precedence than the dereference operator *. So the above parses as:
scanf("%s",(*(A[*sizea-1])));
What you want is:
scanf("%s",((*A)[*sizea-1]));
Similarly, this:
*A[*sizea-1]=(char*)malloc((MAX_CHAR+1)*sizeof(char));
Should be:
(*A)[*sizea-1]=(char*)malloc((MAX_CHAR+1)*sizeof(char));

Segmentation fault (core dumped) with the strcpy-function in c

I am trying to write a function which will read two strings stringArray[MAX]="ABADDFDEFBFCCHCGGEHJJI" and popArr[MAX]="ABCDEFGHIJ" and generate an output like this:
A
B-F-D-A
C-F-D-A
D-A
E-G-C-F-D-A
F-D-A
G-C-F-D-A
H-C-F-D-A
I-J-H-C-F-D-A
J-H-C-F-D-A
However I'm getting a Segmentation fault (core dumped) Error. Why? This is my code:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#define MAX 100
size_t strlstchar(const char *str, const char ch)
{
char *chptr = strrchr(str, ch);
return chptr - str;
}
int main(){
// Input strings
char stringArray[MAX]="ABADDFDEFBFCCHCGGEHJJI";
char popArr[MAX]="ABCDEFGHIJ";
int index=2, lenpop, lentemp;
char usedString[MAX]="";
char tempChar;
lenpop = strlen(popArr);
printf("%c\n", stringArray[0]);
for(int i=1;i<lenpop;i++){
strcpy(usedString, stringArray);
printf("%c", popArr[i]);
tempChar = popArr[i];
while(tempChar!=stringArray[0]){
while(index%2==0){
index = strlstchar(usedString, tempChar);
lentemp = strlen(usedString);
usedString[lentemp-index-1]=0;
}
printf("-%c", usedString[index-1]);
tempChar=usedString[index-1];
index=2;
}
printf("\n");
}
return 0;
}
Thanks in advance!
The segmentation violation occurs in this line:
usedString[lentemp - index - 1] = 0;
Here, you're trying to find the index from the end, but your strlstchar returns the index from the beginning, although it starts searching from the end. And you want truncate the string at the found character, of course.
Replace this line with just:
usedString[index] = 0;
and you get the desired output.

Gettng a segmentation fault(core dumped)

I am getting a segmentation fault on the execution of the code below.The program compiles successfully ,but gives an error on execution.
What is a segmentation fault and how to correct it?
#include<stdio.h>
#include<malloc.h>
#include "sel.h"
#include<sys/time.h>
main(int argc,char *argv[])
{
struct timeval t1,t2;
struct timezone tz;
int i,n;
int *a;
char *num;
FILE *fp;
unsigned long long time1,time2;
fp=fopen("file1.txt","w");
sscanf(argv[1],"%d",&n);
a=(int*)malloc (sizeof(int)*n);
for(i=n;i>0;i--)
{
sprintf(num,"%d\n",i);
fputs(num,fp);
}
fclose(fp);
fp=fopen("file1.txt","r");
i=0;
while(fgets(num,255,fp)!=NULL)
{
sscanf(num,"%d",&a[i++]);
}
gettimeofday(&t1,&tz);
time1=t1.tv_sec*1000000+t1.tv_usec;
sel(a,n);
gettimeofday(&t2,&tz);
time2=t2.tv_sec*1000000+t2.tv_usec;
fclose(fp);
fp=fopen("file2","w");
for(i=0;i<n;i++)
{
sprintf(num,"%d\n",a[i]);
fputs(num,fp);
}
free(a);
printf("\n %llu",time2-time1);
}
Segmentation fault means you had a bad memory access. In this case, you never allocated any memory for num, so you are writing to an uninitialized pointer.

Resources