Search code examples
creversec-stringsfunction-definition

Why does my program stop when I call a function?


I'm coding a function which should reverse a given word or input, but the program keep stopping when I call that.

The code is:

#include <stdio.h>
#define MAX 1000

void reverse(char normal[], char reversed[]);

main() {

    int c, i;
    char line[MAX], reversed_line[MAX];

    for (i=0; (c = getchar()) != EOF && c != '\n'; i++) {
        line[i] = c;
        if (c == '\n')
            i++;
    }
    line[i] = '\0';
    copy(line, reversed_line);
    printf("%s", reversed_line);

    return 0;
}


void reverse(char normal[], char reversed[]) {

    int i, len;

    for (i = 0; normal[i] != '\0'; i++)
        len++;
        
    i = 0;
    while ((reversed[len-i] = normal[i]) != '\0')
        i++;
}

The line where the program stops is copy(line, reversed_line); and the error it gives is [Error] ld returned 1 exit status

Any help will be really appreciated


Solution

  • First of all you do not execute your program only try to compile and link it.

    The error message indicates that the linking has failed as linker has not found the function copy, which indeed is never defined in your code. There is no 'copy' function in the standard library. If you wanted to copy the string or some memory aream you should use strcpy, strncpy, memcpy or memmove.

    But even if the program links you have plenty problems in your code.

    Here is working version of the program:

    #include <stdio.h>
    #define MAX 5
    
    char *reverse(char *normal, char *reversed);
    
    int main(void) {
    
        int c;
        size_t i = 0;
        char line[MAX], reversed_line[MAX];
    
        while((c = getchar()) != EOF)
        {
            line[i] = c;
            if(c != '\n') i++;
            if(i >= MAX - 1) break;
        }
        line[i] = '\0';
    
        reverse(line, reversed_line);
        printf("%s", reversed_line);
    
        return 0;
    }
    
    char *reverse(char *normal, char *reversed) 
    {
        size_t size = 0;
    
        if(normal && reversed)
        {
            while(normal[size]) size++;
            reversed[size] = 0;
            while(size)
            {
                reversed[size - 1] = *normal++;
                size--;
            }
        }
        return reversed;
    }
    

    https://godbolt.org/z/jb7b6hjfT