0

attempting to run the following code, and everything runs fine until i try to strcpy to the test variable/

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

#define MAXTEXT 800

int main()
{
    char test[MAXTEXT] = {0};
    strcpy(test, getstr());
    return 0;
}

getstr(){
    int c, text_pos;
    char text[MAXTEXT] = {0};
    for(text_pos=0; text_pos < MAXTEXT && (c = getchar()) != EOF; text_pos++){
        text[text_pos] = c;
    }
    return text;
}

the the program crashes with a segmentation fault. I'm new to C so I don't really understand what this all means.

thanks.

Nick Kobishev
  • 157
  • 4
  • 13
  • 4
    `text` which is local variable in `getstr`, has gone out of scope and life after `getstr` exits. So it is *undefined behaviour* anyway. – Weather Vane Oct 12 '16 at 15:21
  • 2
    In addition to the core problem of returning a pointer to a local variable, `getstr()` is not a valid function definition in modern C. In the old version of C, that you for some reason use, your function would get translated to `int getstr(void)` which is nonsense. You should get a modern, free compiler and configure it to compile the code as standard C. – Lundin Oct 12 '16 at 15:24
  • as i said, im new to c, currently doing exercises from 'The C programming language' by kernighan and ritchie. i suppose i did miss the return type in the function, also i suppose this kind of function would require the use of pointers, which i haven't covered yet. am i correct? – Nick Kobishev Oct 12 '16 at 15:40
  • 1
    yes, the way to do this is to pass `test` into your `getstr()` function and have the string get constructed in there. No need to return anything from `getstr()` or do a `strcpy` when you return (unless you want a duplicate of `test` for some reason, in which case you'll need `char test2[MAX_CHAR];`) – yano Oct 12 '16 at 16:28

0 Answers0