Pointers dereferencing, bad pointers [closed] - c

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. :)

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.

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).

(C) Trouble with adding integers [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
I'm having troubles with a simple addition calculator.
After I put in the first number, the program crashes.
#include <stdio.h>
int main()
{
printf("Addition calculator\n");
int num1,num2;
printf("Enter the first number: ");
scanf(" %d",num1);
printf("\nEnter the second number: ");
scanf(" %d",num2);
int sol;
sol=num1+num2;
printf("The solution is %d", sol);
return(0);
}
scanf(" %d", &num1);
scanf expects an address of a variable, so it can change its value. You're passing in the value of num1 as an address, which has a very very very high probability to be somewhere your program is not allowed to write.
Same for num2.
I love analogies, so...
Think about this code:
int recordASeven(int x) {
x = 7;
}
int main() {
int y = 0;
recordASeven(y);
printf("y is %d\n", y);
}
This prints 0. Why? It's like this: You have a piece of paper in your locker, with "0" written on it. You copy the "0" carefully onto another piece of paper, give it to a friend and say "write down 7 here instead". He does so, then throws paper away. You look into your locker, and there's your own paper with "0" on it. Because you're passing your friend a copy of your paper and not your own paper, he can't change your own original. Same with functions in C - they can't ever change the variables they get passed in. So scanf can't ever modify the variables directly.
int recordASevenBetter(int *x) {
*x = 7;
}
int main() {
int y = 0;
recordASeven(&y);
printf("y is %d\n", y);
}
Now here you take a blank piece of paper, give him the combination that will open your locker, and give that to your friend, saying "go to my locker, write down 7 on the paper in there". When you go and inspect the paper in your locker later, sure enough, there's "7" on it. In C speak, "&y" will give you the location of where the value of y is ("pointer"), so that anything can change it; "*x" will access the value in the location specified by the value of x.
int recordASevenAndFailMiserably(int *x) {
*x = 7;
}
int main() {
int y = 0;
recordASeven(y);
printf("y is %d\n", y);
}
Finally, here's your problem: you give your friend a copy of your "0", and tell him it's your locker combination. When he goes to open your locker, he gets frustrated, trashes your room and pees on the floor.
In this case, the compiler can detect the disparity, since there is a clear mismatch between the declared and the provided types, and the compiler will refuse to do it. But scanf uses variadic argument list, which means the declaration does not list the parameter types. It will be the responsibility of scanf to decypher the format and interpret the bag of bytes it gets as something sensible. And the compiler can only stand by and watch shaking its head (when you enable warnings) as you lie to scanf about what you're giving it.
Please change it to &num1 and &num2 as mentioned by Amandan. You have to pass the address of the variable.

Can't get my code to work properly [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
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.
Closed 8 years ago.
Improve this question
Task says:
Given a string, compute recursively a new string where all the 'x' chars have been removed.
My code:
#include<stdio.h>
#include<string.h>
char c[50];
int xx(char a[],int b,int d){
if(a[b]=='\0')
return a;
else if(a[b]=='x'){
c[d]=a[b+1];
return xx(a,b+2,d+1);}
else {
c[d]=a[b];
return xx(a,b+1,d+1);
}
}
int main()
{
char a[50];
scanf("%s",a);
xx(a,0,0);
printf("%s",c);
return 0;
}
As long as I don't type x next to the other x it works. Like if i type xaxb, the result will be ab.
But if I type xxaxxb, the result will be xaxb...
Your code skips over a potentially important character - a '\0' or an 'x' in these three lines:
else if(a[b]=='x'){
c[d]=a[b+1];
return xx(a,b+2,d+1);
}
This code goes ahead and copies the a[b+1] without checking that character at all.
You shouldn't copy anything there - just advance b by 1, and keep d as is:
else if(a[b]=='x'){
return xx(a,b+1,d);
}
This way the next level of invocation would check a[b+1] for you, stopping or removing it as needed.

Resources