Why is the error "Segmentation fault" here? [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 6 years ago.
Improve this question
I tried to implement the recursive form of Selection sort. But error as "Segmentation fault " is being shown. Where is the error? What are the errors generally faced with recursive algorithms?
#include <stdio.h>
void ssort(int[],int,int);
void prints(int[],int);
void sorting(int[],int,int);
int a[]= {5,6,3,1,2,4};
int main()
{
ssort(a,0,6);
prints(a,6);
return 0;
}
void ssort(int a[],int s,int e)
{
int min=a[s];
int ch,p,j;
for(j=s+1; j<e; j++)
{
if(min>a[j])
{
min=a[j];
ch=j;
}
}
sorting(a,j,ch);
if(s+1<e)
{
ssort(a,s+1,e);
}
}
void prints(int a[],int n)
{
int i;
for(i=0; i<n; i++)
printf("%d",a[i]);
}
void sorting(int a[],int j,int ch)
{
int p=a[j];
a[j]=a[ch];
a[ch]=p;
}

Segmentation fault is thrown when illegal memory is accessed. There is a possibility that "sorting(a,j,ch);" may get called even when the code may not have gone through the if block inside the prededing for-loop. In that case value of "ch" may be unpredictable and then when u access a[ch] inside the sorting(..) function, it may be access some illegal memory which will cause segmentation fault

Comment by BLUEPIXY in the question pretty much solves the problem. Writing this to add why those changes are needed.
ISSUE 1: At each step of recursion you will store the minimum value in first index (for that level of reursion). To do this first you identify the index of the minimum value, which in your code you are stroing in ch. Then you swap the values in first index and the index with minimum value. That means your code should be swapping the values in indexes s and ch. But, you are swapping the values in last index and the index with minimum value. So you need to make the below change:
/* sorting(a,j,ch); */ // ISSUE: you are swapping with last index
sorting(a, s, ch); // CORRECT: you are swapping with first index
ISSUE 2: If the condition if(min>a[j]) is never true then ch = j; is never executed, and ch will have indeterminate value. And then when you call sorting(a, s, ch); your program will not have deterministic results, and it may even crash. So, you have to set s as the minimum index at the beggning, as:
/* int ch,p,j; */
int ch = s, p,j; // Initialize ch with starting index
These changes should resolve you issue. However, one change you can make is, swap the values only if need:
/*sorting(a,j,ch);*/
if (ch != s)
sorting(a, s, ch);
And finally, you may want to change the name of the function sorting to swap.

Related

Converting char array to upper case in C [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 3 years ago.
Improve this question
I'm trying to convert a char array to upper case in C. But it still prints out in lower case. The logic in conversion function looks okay to me. I don't know if the problem could be that the input I'm passing to this function is member of a structure variable.
This is the structure whose member I'm passing to conversion function:
typedef struct AESParams {
unsigned char output[192];
} AESParams;
My conversion fucntion is shown below:
void stringUpr(char *s)
{
int i=0;
while(s[i]!='\0')
{
if(s[i]>='a' && s[i]<='z'){
s[i]=s[i]-32;
}
++i;
}
}
I call conversion function as follows:
AESParams parameters;
stringUpr(parameters.output);
If I print the output after calling "stringUpr" function, the value is still in lower case. Can anyone tell me what might be causing the issue here?
TIA...
Update: Code that writes value to output.
EVP_EncryptUpdate(&ctx, parameters->output, &outLen, input, length);
// This call happens in some other file. parameters is passed to the function that calls this function and after computation parameters is passed back to the place where I'm calling stringUpr().
I'm confident that this lines works and it gives the correct results after computation. It's just that I want to take this value and convert to upper case and write to a file.
Your program assumes that it's running using an ASCII character set, which is not guaranteed. Use the standard functions defined in ctype.h
void stringUpr(char* s)
{
int i = 0;
while(s[i] != '\0')
{
s[i++] = toupper((unsigned char)s[i]);
}
}

impacting Strings with pointers [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 5 years ago.
Improve this question
The code which does not work. In function main after initializing variables by the user, it goes to if part and after that crash happens. This program's goal is to impact the repetitive characters in the string. So I decided to have a pointer in a function f1 and the pointer should point to 0th char of the array kar[]
then compare the 0th char to 1st char but the program crashes exactly after the last scanf("%s",kar[1000]).
where is the problem?
#include <stdio.h>
char f1(char* p)
{
int i=0,c=1;
while(*(p+i))
{
if(*p==*(++p))
{
c+=1;
p++;
i++;
continue;
}
else
{
if(c>1)
{
printf("%c%d",*p,c);
}
else
{
printf("%c",*p);
}
}
i++;
}
}
int main()
{
int n,i,m;
char kar[1000];
scanf("%d",&n);
for(i=1;i<=(2*n);++i)
{
scanf("%d",&m);
scanf("%s",kar[1000]);
if(m==1)
{
f1(kar);
}
}
}
This
scanf("%s",kar[1000]);
should trigger a compiler warning, as you pass a char where a char* is expected. You pass the 1001st element of kar (which is out of kar's bounds, BTW). In C array indices start with 0 for the 1st element.
To scan into kar, just pass the address of kar's 1st element.
scanf("%s", &kar[0]);
As arrays get decayed to the address of their 1st element when being passed to a function the following statement is equivalent
scanf("%s", kar);
Please note that the above two statements very well allow the user to enter more characters then kar can hold and with this make scanf() overflow kar, that is write beyond it bounds, invoking undefined behaviour, which might crash your program or whatever ...
To avoid this tell scanf() the maximum to scan by doing:
scanf("%999s", kar);
The maximum for chars a strings can hold in C is always one less then defined as C strings need one more char to have their end marked by a '\0'terminator.

What will be the result of next function and array in main? [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 5 years ago.
Improve this question
today i tried to do something new,but i didn't do that correct.Would anyone be able to do that and explain why is it so like that? Thank you in advance
#include<stdio.h>
void function(int a[],int n)/*The definition of function with void type,with parameters
int a[],int n */
{
int i;// declared count,type integer//
for(i=0;i<n;i++)//count goes from 0,to <n,and increment all time while goes//
printf("%d",a[i++]);// printing on the screen integers (a[i],i=i+1)//
printf("\n");// printing the newline //
}
main()
{
int a[]={1,2,3,4,5,6,7}; // declaration of array with 7 elements //
int n=5;// declaration of variable n type integer value of 5 //
function(a,n) // calling the function with parametres a,n//
} // end of sequence //
In my case i got the result of the 1,2,3,4,because i tought that the count goes from 1,to the one number less than n=5,but the IDE show the result of 135 ,i think the problem in my way is with counter...but all advices are welcome,thanks
Please make sure you are posting properly formatted valid C code.
Note that what you get is not one hundred and thirty five, but one, three, and five. You get that because you are incrementing the loop counter twice.
Here's a working, more readable version:
#include <stdio.h>
void function(int a[],int n)
{
int i;
for(i = 0; i < n; i++)
printf("%d ",a[i]);
printf("\n");
}
int main(void)
{
int a[]={1,2,3,4,5,6,7};
int n=5;
function(a,n);
return 0;
}
replace
printf("%d",a[i++]);// printing on the screen integers (a[i],i=i+1)//
with
printf("%d",a[i]);// printing on the screen integers (a[i],i=i+1)//
in your code you were incrementing i twice. Once in the while and once in the a[i++]

Why a for loop isn't considered 'stylish' by my teachers? [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 9 years ago.
Improve this question
I had to write a piece of code which would search a given value in an array.
I made this piece of code, which works:
#include <stdio.h>
int index_van(int searchedValue, int array[], int lengthArray)
{
int i ;
for (i = 0; i < lengthArray; i++)
{
if (array[i] == searchedValue)
{
return i;
}
}
return -1;
}
int main()
{
int array2 [] = {0, 1, 3, 4, 5, 2};
printf("%i", index_van(2, array2, 6));
}
With the correction (the teacher put up online) of this exercise the notes of my teacher were:
You have to quit the moment you have found your value ,so you can't search through the entire table if you have found your value already. A for-loop therefore isn't tolerated.
Even if the for-loop has an extra built-in condition, THIS ISN'T STYLISH!
// One small note ,she was talking in general . She hasn't seen my version of the exercise.
So my question to you guys is, is my code really 'not done' towards professionalism and 'style' ?
I think she's implying that you should use a while loop because you don't know how many iterations it will take to get you what you're looking for. It may be an issue of her wanting you to understand the difference of when to use for and while loops.
"...Even if the for-loop has an extra built-in condition..."
I think this right here explains her intentions. A for loop would need a built-in condition to exit once it's found what it's looking for. a while loop already is required to have the condition.
There is nothing wrong with your code. I have no idea if using a for loop is less stylish than using another, but stylish is a very subjective attribute.
That being said, don't go to your teacher and tell her this. Do what she says, a matter like this is not worth contradicting your teacher for. Most likely this is just a way to teach you how while loops work.
After accept answer:
I've posted this to point out sometimes there is so much discussion of "style", that when a classic algorithmic improvement is at hand, it is ignored.
Normally a search should work with a const array and proceed as OP suggest using some loop that stops on 2 conditions: if the value was found or the entire array was searched.
int index_van(int searchedValue, const int array[], int lengthArray)
But if OP can get by with a non-const array, as posted, then the loop is very simple and faster.
#include <stdlib.h>
int index_van(int searchedValue, int array[], int lengthArray) {
if (lengthArray <= 0) {
return -1;
}
int OldEnd = array[lengthArray - 1];
// Set last value to match
array[lengthArray - 1] = searchedValue;
int i = 0;
while (array[i] != searchedValue) i++;
// Restore last value
array[lengthArray - 1] = OldEnd;
// If last value matched, was it due to the original array value?
if (i == (lengthArray - 1)) {
if (OldEnd != searchedValue) {
return -1;
}
}
return i;
}
BTW: Consider using size_t for lengthArray.

Write recursive function that prints 1 and n zeroes in C [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I have trouble writing a recursive function in C:
void func(int n)
which for a given number n prints "1" and n zeroes after it.
for example:
func(3);
prints: 1000
func(5);
prints: 100000
No global variables (outside the function) are allowed and argument count must not be increased. No other helper functions allowed.
Just some pointers:
Why do you think you must print "1" only on the first call of the function?
Why can't you print it on the last call of the recursive function and then print all the 0's?
How will you determine if a call to the function is the last call in the recursive way? (Can the value of "n" hold the answer?)
I would suggest you look into static variables. you could set a static variable to tell if your function is being called recursively or not. If you're not allowed to use global variables, it's just a tricky work-around. And when your recursion is done, just set it back for the next call.
You can solve this problem using two functions, for example func and func_rec. func will print the 1 and it will once call the recursive function func_rec which will print only zeros (recursively).
#include <stdio.h>
void func(int k){
if(k==0){
printf("1");
return;
}
func(k-1);
printf("0");
}
int main(){
func(3);
return 0;
}
#include <stdio.h>
void func(int n)
{
static one = 1;
if (one == 1){
printf("1");
one--;
func(n - 1);
}
else {
if (n < 0){
printf("\n");
return;
}
else {
printf("0");
func(n - 1);
}
}
}
int main() {
func(5);
return 0;
}
The code is very trivial so, even it seems that its a homework, i'm giving out the code.
Your earlier question suggests that you are not so much into c coding. What i'm trying to do is to reduce your frustration by giving out the code, but with a twist.
Please answer us why the code i've given is not a "pure" function? why this solution should be discarded with ones which have global storage.
You should learn this stuff, its pretty interesting :)

Resources