segmentation fault in C programme [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
#include<stdio.h>
int encryption_check(char* s , char* t)
{
printf("%s",s);
int i=0 , diff = t[0] - s[0];
while(s[i]!='\0' && t[i]!='\0')
{
if(t[i]-s[i]<=0)
{
return -1;
}
else if(t[i]-s[i]!=diff)
{
return -1;
}
}
return diff;
}
int main()
{
int d = 0;
char s[]= "abc";
char t[]= "def"; // s=plain text and t=cipher text
d = encryption_check(s,t);
printf("%d",d);
return 0;
}
encryption_check() returns the difference between ciphered and plain text.
This is giving segmentation fault for some reason.
Also I would like to know how to pass strings of random (not fixed) length to encryption_check().

If not getting into details of what your encryption_check should actually do and keep it short, your while loop can't terminate as your i never changes after being set to 0.
On the first run, s[0] = 'a' and t[0] = 'd' so t[0] - s[0] = 3 and so the conditions in while will be true. On the consequent runs, as you don't iterate i, the loop won't stop.
To fix it, just add i++ as below:
while(s[i]!='\0' && t[i]!='\0') {
if(t[i]-s[i]<=0) {
return -1;
} else if(t[i]-s[i]!=diff) {
return -1;
}
i++;
}

Related

remove duplicates in a string with a buffer [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I’m trying to remove duplicates in a string using a map. Running it through GDB I'm not able to figure out where the code is failing, though the logic to me seems right.
Could anyone please point out the mistake?
int main() {
char *str="I had my morning tea";
int len = strlen(str);
int dupArr[256] = {0};
//Build the map
int i=0;
for(i;i<256;i++)
dupArr[str[i]]++;
//If the count is 1 then print that value.
i=0;
for(i;i<256;i++) {
if(dupArr[str[i]] == 1) {
printf("%c\n",str[i]);
}
}
}
output
I h y o r i g t % c 4 # } ` 8 � F J
I get up to 't' ,which is correct but then i see magic chars.
Your string has length of len but you are traversing till 256 which is out of bound.
Use len when inserting into the hash.
int i=0;
for(i;i<LEN;i++)
dupArr[str[i]]++;
Also if your are checking the duplicates then it should be bigger than 1 since your are ++ the first encountered char
if(dupArr[str[i]] > 1)
In addition to Mark Ezberg's good answer, note that dupArr[str[i]]++; poses a problem when str[i] < 0.
Better to treat the characters as unsigned char:
int dupArr[UCHAR_MAX + 1] = {0};
....
dupArr[(unsigned char) str[i]]++;
Rolling this and other ideas together:
int main(void) {
char *str="I had my morning tea";
size_t dupArr[UCHAR_MAX + 1] = {0};
unsigned char *s = (unsigned char *) str;
while (*s) {
dupArr[*s]++;
s++;
}
for(unsigned i = 0; i <= UCHAR_MAX; i++) {
// A duplicate is when dupArr[i] is _more_ than 1.
if(dupArr[i] > 1) {
printf("%c\n",str[i]);
}
}
}

C Segmentation fault function reference [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
The if(ptr->is_word) on the sizeH(node *ptr) function is causing a segmentation fault.
dictionary.c:120:13: runtime error: member access within null pointer of type 'node' (aka 'struct node')
dictionary.c:120:13: runtime error: load of null pointer of type '_Bool'
Segmentation fault
If I add an if condition to return a specific value before this if-condition, the code executes and I make sure the root isn't null
so I guess the problem is the ptr isn't passed correctly to the sizeH function.
unsigned int size(void)
{
node *ptr = root;
printf(ptr->is_word ? "true" : "false");
unsigned int count = sizeH(ptr);
printf("COUNTER IN SIZE %d\n" , count);
return 0;
}
unsigned int sizeH(node *ptr){
if(ptr->is_word)
{
return 1;
}
else
{
for(int x = 0; x < N; x++){
return 0 + sizeH(ptr->children[x]);
}
}
return 0;
}
There's a couple of fundamental problems with your sizeH function. Firstly it doesn't check that the ptr that is passed in is not NULL. This is very likely to happen as your function is recursive and you have this loop that is called for each child node.
for(int x = 0; x < N; x++){
return 0 + sizeH(ptr->children[x]);
}
Except that the code in the loop is wrong and it'll only ever be called for the first child, which is the second issue. Because you use return inside the loop, it'll only ever run once. Instead you should tally up the values returned for each child node and then return that.
Making the two changes above would leave your function looking like this.
unsigned int sizeH(node *ptr) {
if(ptr==NULL) {
return 0;
} else if(ptr->is_word) {
return 1;
} else {
unsigned int ret = 0;
for(int x = 0; x < N; x++) {
ret += sizeH(ptr->children[x]);
}
return ret;
}
// return 0; This isn't needed - the code will never reach here.
}
It's also worth picking one coding formatting style and sticking to it rather than using a mixture as it makes for neater code.

Is this reverse string function in C poorly written ? / How to make this code better? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Here is a part of code which describes a function to reverse characters of a string
(Based on exercise 1-19 of Brian W. Kernighnan Programming in C)...
( I have googled various text reverse function, but all of them us pointers or using strrev(), but I don't have an idea what a pointer is.... nor do I want to use strrev(), hence I made a reverse string function as the author wanted it to be........ )
The function:
void reverse(char s[])
{
int i , n ;
char j ;
i = 0 ;
while(s[i] != '0') //And not EOF
{
++n;
}
for(i = 0; i < n; ++i)
{
j = s[i] ;
s[i] = s[n - 1] ;
s[n - 1] = j ;
}
}
However I think overwritting arrays is bad , and the whole function seems awry.
P.S : It would be great if you did check and help me with the whole code here, since it would be offtopic if I did post it here, The code's main return 0; however it still doesn't work....
[EDIT]
Ok I am seriously sorry for troubling you for a typo... I can't delete this question since it has answers with upvotes however I'm sorry....
The correct function would be :
void reverse(char s[])
{
int i, l;
char temp;
for (l = 0; s[l] != '\0'; ++l);
l--;
for (i = 0; i < l; ++i) {
temp = s[i];
s[i] = s[l-1];
s[l-1] = temp;
--l;
}
}
Full Code is here :
Code
Code Working is here :
UPDATE:
I created a correct and working solution for the word 'hello':
#include <stdio.h>
int main(void)
{
char s[] = "hello";
char temp;
// do the swapping here..
temp = s[0];
s[0] = s[4] ;
s[4] = temp ;
temp = s[1] ;
s[1] = s[3] ;
s[3] = temp ;
temp = s[2] ;
s[2] = s[2] ;
s[2] = temp ;
printf("%c, %s ", temp, s);
}
I don't know where you got this piece of code, but it's actually quite broken:
n is never initialized. This is undefined behavior.
The while loop won't terminate at all because it compares a char with a value that is not in the range of a char.
The while loop can't do anything sensible since its body can't change the loop condition.
The for loop exchanges all characters with one single array element, which effectively rotates the string right by one char. But the program will never reach this point anyway.
The loop
while(s[i] != EOF)
{
++n;
}
seems wrong.
String end is checked via 0, not via EOF.
You never change i, so that you always check s[0].

How to find whether the string is a Lapindrome? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
The following code is giving correct output as given on the codechef problem page: http://www.codechef.com/problems/LAPIN
but getting wrong answer on submission
please tell me the possible problem with my code
here is the question
Lapindrome is defined as a string which when split in the middle, gives two halves having the same characters and same frequency of each character. If there are odd number of characters in the string, we ignore the middle character and check for lapindrome. For example gaga is a lapindrome, since the two halves ga and ga have the same characters with same frequency. Also, abccab, rotor and xyzxy are a few examples of lapindromes. Note that abbaab is NOT a lapindrome. The two halves contain the same characters but their frequencies do not match.
Your task is simple. Given a string, you need to tell if it is a lapindrome.
Input:
First line of input contains a single integer T, the number of test cases.
Each test is a single line containing a string S composed of only lowercase English alphabet.
Output:
For each test case, output on a separate line: "YES" if the string is a lapindrome and "NO" if it is not.
and here is the code
#include<stdio.h>
#include<string.h>
int main()
{
int f,t,mid,len;
char arr[1000];
int left[125],right[125];
scanf("%d",&t);
for(int i=0;i<t;i++)
{
f=0;
scanf("%s",arr);
memset(left,0,sizeof(left));
memset(right,0,sizeof(right));
len=strlen(arr);
for(int i=0;i<len/2;i++)
left[arr[i]]++;
for(int i=(len+1)/2;i<len;i++)
right[arr[i]]++;
for(int i=0;i<strlen(arr);i++)
{
if(left[arr[i]]!=right[arr[i]])
f++;
break;
}
if(f==0)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}
I recommend you read up on modularity; it'll make your life easier.
#include <stdio.h>
#define BOOL unsigned char
#define TRUE 1
#define FALSE 0
unsigned string_length(char *string)
{
unsigned counter = 0;
while (string[counter++] != '\0') { }
return counter - 1;
}
BOOL are_equal(unsigned *a, unsigned *b, int size)
{
int i;
for (i = 0; i < size; ++i)
{
if (a[i] != b[i])
{
return FALSE;
}
}
return TRUE;
}
BOOL is_lapindrome(char *string)
{
unsigned left[26] = { 0 }, right[26] = { 0 },
str_len = string_length(string);
if (str_len < 2)
{
return FALSE;
}
int i;
for (i = 0; i <= str_len / 2 - 1; ++i)
{
left[string[i] - 'a']++;
}
for (i = (str_len + 1) / 2; i < str_len; ++i)
{
right[string[i] - 'a']++;
}
return are_equal(left, right, 26);
}
int main()
{
char *list[6] =
{
"gaga",
"abcde",
"rotor",
"xyzxy",
"abbaab",
"ababc"
};
int i;
for (i = 0; i < 6; ++i)
{
printf("%s\n", is_lapindrome(list[i]) == TRUE ? "YES" : "NO");
}
return 0;
}
Your buffer is one byte too short - a string of 1000 characters requires 1001 chars, the last one taken by the nul terminator.
"lowercase English alphabet" sounds a bit ambiguous - I'd say that by some interpretation, it could contain spaces. If so, the input will be read incorrectly.
I can't see other problems right now, but I'd strongly suspect the first one.

Stop for loop upon returning value [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
This is the relevant function:
int computerChoice() {
int x, y;
for (y=0;y<=2;y++) {
for (x=0;x<=2;x++) {
if (matrix[y][x] == 'a') {
return(1);
} else {
matrix[y][x] = 'b';
return(0);
}
}
}
}
And this is the relevant main() code:
char matrix[3][3];
int duplicate1 = 0;
do {
duplicate1 = computerChoice();
} while(duplicate1 == 1);
I'm attempting to scan through a 3x3 two dimensional array and check sequentially if each one is equal to "a". If so I want the function to return a "1" and continue checking. Once it finds an entry that is not equal to "a" it should set that entry equal to b, return 0 and stop looping.
I get some really weird results. If [1][1] has an "a" in it, the function doesn't do anything but just "freezes". If [2][2] has an "a" in it, the function correctly places a "b" in the entry [1][1].
This also happens if other entries are already filled.
Any thoughts?
your implementation seems buggy the code should continue till it is finding 'a' in each cell.If it doesn't find 'a' it should set it to 'b' and return 0. the loop will stop automatically when you return.
If both the loop completes that means every cell in matrix contains 'a'. and you should return 1;
int computerChoice() {
int x, y;
for (y=0;y<=2;y++) {
for (x=0;x<=2;x++) {
if (matrix[y][x] == 'a') {
continue;
}
else {
matrix[y][x] = 'b';
return(0);
}
}
}
return 1;
}
I'm assuming what you mean is "I want to process the entire array, and return 1 if I ever found an a, and 0 otherwise". That can be achieved like so:
int found = 0;
for (size_t i = 0; i != 3; ++i)
{
for (size_t j = 0; j != 3; ++j)
{
if (matrix[i][j] == 'a') { found = 1; }
else { matrix[i][j] = 'b'; }
}
}
return found;
(By changing to ++found, you can also return the number of occurrences of 'a'.)
If on the other hand you want to return 0 as soon as you know there's a non-'a' in your data, it's simpler:
for (size_t i = 0; i != 3; ++i)
for (size_t j = 0; j != 3; ++j)
if (matrix[i][j] != 'a') { matrix[i][j] = 'b'; return 0; }
return 1;
I don't exactly understand what you mean by "return 1 and continue checking". I will assume that you want to scan the whole array, and return 1 if every position is an a; otherwise, return 0 and set the first position that was not an a to b. Here's the code:
int computerChoice() {
int x, y;
for (y=0;y<=2;y++) {
for (x=0;x<=2;x++) {
if (matrix[y][x] != 'a') {
matrix[y][x] = 'b';
return 0;
}
}
}
return 1;
}

Resources