impacting Strings with pointers [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 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.

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]);
}
}

scanf reading totally different number [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
Here is all the code I have in Visual Studio:
#include <stdio.h>
int main (void) {
int input;
puts("There are 10 seats available on the next flight");
puts("Where would you like to reserve a seat?");
puts("Please type 1 for First Class");
puts("Please type 2 for Economy");
scanf("%d", &input);
if (input == 1) {
printf("You Typed %d\n", &input);
}
if (input == 2) {
printf("You Typed %d\n", &input);
}
}
But when I run the program I get output that says:
There are 10 seats available on the next flight
Where would you like to reserve a seat?
Please type 1 for First Class
Please type 2 for Economy
1
You Typed 6159588
Press any key to continue . . .
I get a totally random number every time. Because of this I can't seem to get anything I write after the input to work. Why is this happening?
What you get printed out is the address of the variable input, not its value! This is because printf accepts its arguments by value - simply because they can be passed like that. What you need thus is
printf("%d", input); // without the ampersand!
scanf - in contrast - is fundamentally different. It is going to place a value into a variable you provide to it - and therefore needs a pointer.
Simple example:
int n = 7;
void myPrintf(int v)
{
++v;
}
void myScanf(int* v)
{
++*v;
}
int main(int argc, char* argv[])
{
myPrintf(n); // n passed by value, cannot be modified
// (but printf does not intend to, either!)
myScanf(&n); // n will be incremented!
// (scanf does modify, thus needs a pointer)
return 0;
}
Back to the roots, though: There is still a fundamental problem: You are passing a pointer, but evaluate it as an int. If sizes of both differ - which is the case on modern 64-bit hardware - you are in trouble. The value then is read from the stack with different size and part of your address actually gets discarded (pointer addresses require "%p" format specifier, assuring that the apprpriate number of bytes is read from stack - in case of modern systems 8 vs. 4 for int).

Why is the error "Segmentation fault" here? [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 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.

Why is my code ignoring the while? [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 8 years ago.
Improve this question
So here is the code, it ignores the while and I don't know why, it is supposed to start with the while as soon as you enter a value for the first printf
#include <stdio.h>
int main()
{
str WhoOwes,Fabri,Alen,Amilcar,Maxi,Lolo;
int RandomInt=0,Deudores;
printf("How many people owes?:");
scanf("&d",&Deudores);
while(RandomInt <= Deudores);
{
printf("who owes?:");
scanf("&c",&WhoOwes);
if(scanf("%c",&WhoOwes)==Fabri)
{
Fabri= Fabri+1;
printf("Fabri debe $",Fabri*4);
}
}
return 0;
}
Thanks!H
Change:
while(RandomInt <= Deudores);
To (remove the semicolon):
while(RandomInt <= Deudores)
Also, the delimiter you use in scanf should be %d not &d.
Further more, what type is str?
You are using scanf delimiter%d which is for an int to store into a str type which, I assume is some sort of a struct. If it is, this is not the way to do that. You have to store information into each part of the struct separately. Or change the type str to an int. This could be the reason why your while loop doesn't happen because you are trying to compare an int to a str:
while(RandomInt <= Deudores); // Deudores is a str
Then you are reading information twice by calling scanf() twice but you are only comparing what you get the second time. Also, the first time you read it you use the &c delimiter which is invalid. It should be %c. Further more, you create the str Fabri variable above with an invalid type str and also you don't give it a value anywhere in your code so you cannot do the comparison in the if statement:
scanf("&c",&WhoOwes);
if(scanf("%c",&WhoOwes)==Fabri)
Since you are using the character delimiter %c, you should declare WhoOwes and Fabri as char types to have consistent logic although it isn't technically required since int and char store interchangeable information. You must also initialize the Fabri variable to some char value.
However, in the end of your code you have the statement:
printf("Fabri debe $",Fabri*4);
This will not work because you are missing a delimiter where to print the Fabri*4 value.
Change that line to:
printf("Fabri debe %d$",Fabri*4); // add the %d delimiter to print the actual value
Since you are using Fabri in a calculation, you should then probably declare all your variables as int and read them using the %d delimiter, not %c.
Your program should look something like this:
#include <stdio.h>
int main()
{
int WhoOwes, Fabri, Alen, Amilcar, Maxi, Lolo; // these are int types not str types
int RandomInt = 0, Deudores;
Fabri = 5; // initialize Fabri to some value that can be used for comparisons
printf("How many people owes?:");
scanf("%d",&Deudores);
while(RandomInt <= Deudores);
{
printf("who owes?:");
scanf("%d",&WhoOwes); // use
if(WhoOwes == Fabri) // use what you scanned the first time to compare to Fabri
{
Fabri= Fabri+1;
printf("Fabri debe %d$",Fabri*4); // add the int delimiter %d to actually print the money amount
}
}
return 0;
}

Pointers dereferencing, bad pointers [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I am trying to program an encrptor and decryptor. My problem is a pointer that I assigned value first still has the same value as the second. I tried to use free but the problem is still the same.
For example, I typed aslkdjlasc(sample only)
and the output would be:
helloworld
I try to run the program again, then I type daskjda
the output would be like
doctorxRLD
RLD is from the past value of this pointer. It's supposed to be 7 characters only, but since helloworld is 10, the first 7 letters are replaced by the encryption but the last 3 characters are still printed.
What do I do?
UPDATE: HERE IS PART OF THE CODE:
void encrypt(char *crypt)
{
char *plaintext,*encryption,slash=0x2F;
int i,j,k,flags,f;
encryption=(char *)malloc(sizeof(int));
plaintext=(char *)malloc(sizeof(int));
printf("Enter plaintext, spaces,commas,and dots should be represented as /:\n");
scanf("%s",&*plaintext);
for(i=0;i<strlen(plaintext);i++)
{
j=1;flags=0;
while(j<53 && flags==0)
{
if(plaintext[i]==slash)
{
encryption[i]=slash;
flags=1;
}
if(plaintext[i]==crypt[j])
{
encryption[i]=crypt[j-1];
flags=1;
}
k=j+2;
j=k;
}
}
printf("%s",encryption);
free(encryption);
free(plaintext);
getch();
}
HERE IS THE MAIN
main()
{
char c;
int timer;
char crypt[53]="***i have hidden my encryption code***";
clrscr();
printf("Press e to encrypt, d to decrypt, ESC to exit.\n");
c=getch();
switch(c)
{
case(0x1b):
exit(0);
break;
case(0x64):
decrypt(crypt);
break;
case(0x65):
encrypt(crypt);
break;
default:
printf("INVALID. FORCE EXIT IN 3 SEC0NDS.");
delay(3000);
exit(0);
}
getch();
}
In your code you are allocating integer size (4 bytes ) of memory for a string
When you do
plaintext=(char *)malloc(sizeof(int));
Then by doing this
scanf("%s",&*plaintext);
your are possibly scanning a string of size more than that four characters ( however you allocated only four bytes) also
scanf("%s",&*plaintext); is equivalent to scanf("%s",plaintext); ( with the previous statement you are adding unnecessary computations.
it's me. I got it already. Thanks to all your comments though some are harsh. haha
I refrained from using malloc because apparently DCoder points out I do not know how to use them.
Thanks Sanyam Goel I have fixed my scanf too.
I used only 2 pointers instead of 4. What I did was I instantiated them in the main function instead of in each of the decrpyt and encrypt functions. Like this:
main()
{
char c,*from, *to; ..........
void encrypt(char *crypt,char *plaintext,char *encryption)
void encrypt(char *crypt,char *ciphertext,char *decryption)
So when I call either of them, I just put:
case(0x64):
decrypt(crypt,from,to);
break;
case(0x65):
encrypt(crypt,from,to);
break;
And at the end of the switch in the main function:
free(from); from=NULL;
free(to); to=NULL;
So now I have eliminated unnecessary pointers and extra processes.
THANK YOU EVERYONE. :)

Resources