cstring

Reversing a word in c


It is for sure simple but I am quite a newbie to C and I don't understand why the following code is bugging. The code is a simple reverting character position of a string :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{   int i,length;
    char *word;
    scanf("%s",word);
    length = strlen(word);
    char res[length];

    for(i=0;i<length;i++){
        res[i]=word[length-1-i];
        printf("%d",res[i]);}
}

when I enter a string, I get a message : (lldb) in the console, and in the debugger : movb %al, (%rcx), EXC_BAD_ACCESS(code=1,address=0x0)


Solution

  • char *word;
    scanf("%s",word);
    

    Invalid write to non existent memory location.

    Create an array like so: char word[MAXSIZE] or use malloc or calloc to allocate memory dynamically. And use fgets not scanf

    Some links to get you on your merry way: malloc,calloc,fgets