0

So I have the following function defined in C:

#include <stdio.h>

void encrypt(int size, unsigned char *buffer){
    buffer[i] = buffer[i] + 1;
    printf("%c",buffer[i]);
}

int main(){
    encrypt(5,"hello");
}

I'm expecting this to return ifmmp, but instead I get the error

"Segmentation fault (core dumped)".

If I get rid of the line
buffer[i] = buffer[i] + 1
and
printf("%c",buffer[i]+1)
then I get the desired result. But I would like to actually change the value stored in that address. How can I do this?

16
  • 5
    Your code doesn't compile. Commented May 31, 2016 at 17:43
  • 2
    "hello" is a const readonly data you can't increment it since it's not a variable. Try using character array instead. Commented May 31, 2016 at 17:43
  • 4
    Turn on all your compiler warnings. Commented May 31, 2016 at 17:43
  • 1
    Dont pass "hello" as it is a string literal and a constant . Use char s[]="hello"; as suggested by @cleblanc . Commented May 31, 2016 at 17:46
  • 1
    There's a code smell in there, what's size, not used. What's i, not used either. Back to drawing board there I guess. Commented May 31, 2016 at 17:46

1 Answer 1

1

There are many problems in your code :

  • i is uninitialized
  • "hello" is converted to int, so avoid sending that way. instead see the code bellow
  • you've sent argument size but haven't used it.

  • finally, use a loop to increment every value in the array char *buffer

  • return a value at the end of main() as you mentioned return type as int

So, here's the code

#include <stdio.h>

void encrypt(int size, char *buffer){
    int i;
    for(i=0;i<size;i++)
        buffer[i] =(buffer[i]+1);
    printf("%s",buffer);
}

int main(){
    char s[]="hello";// total 5 charcters + '\0' character
    encrypt(5,s);
    return 0;
}

the output generated is as desired.

Sign up to request clarification or add additional context in comments.

4 Comments

Well, two out of four isn't terrible, I suppose. And did you compile this, or are you leaving the task of discovering a char[5] can't possibly hold "hello" (hint: nulchar terminator?) as an exercise to the OP?
Yes I compiled @WhozCraig do you mean I mentioned only 2 problems?
@WhozCraig i updated my answer, i think it has no issues now.. And BTW thanks for mentioning th null character issue
@Mr.Pickles if you have any doubts regarding my code, you can ask me