Jake Badlands
Jake Badlands

Reputation: 1026

could not pass a char array properly

One function tries to pass char array to another, but without success:

char * ret() {
    char buf[32];
    buf[0]='1'; // buf char array contains 1
    buf[31]='\0';
    printf(buf);
    return buf;
}

int multiline() {
    char temp[32];
    strcpy(temp,ret()); // temp array doesn't contain 1 after this line
    temp[31]='\0'; 
    printf(temp);
}

Please tell me, how to fix this issue?

Upvotes: 0

Views: 128

Answers (3)

sverre
sverre

Reputation: 6919

You can fix the issue by not returning a local variable (allocate a string or return a pointer to a statically allocated one):

char * ret() {
    char * buf = malloc(32*sizeof(char));
    buf[0]='1'; // buf char array contains 1
    buf[31]='\0';
    printf(buf);
    return buf;
}

int multiline() {
    char temp[32];
    char * returnedString = ret();
    strcpy(temp,returnedString);
    free(returnedString);
    temp[31]='\0'; 
    printf(temp);
}

Upvotes: 1

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81694

You can't return a pointer to a local variable; as soon as the function returns, the local variable, along with the rest of the function's stack frame, is destroyed.

Instead, you can return a copy of the array; you could make one using strdup().

As an aside, you're setting the first character of your array, and putting a \0 at the end, but the 30 characters in between just hold garbage. Normally the \0 at the end of a string is immediately after the valid characters, not all the way at the end of the array.

Upvotes: 1

thumbmunkeys
thumbmunkeys

Reputation: 20764

you are returning a pointer to a local variable char buf[32];. This array is allocated on the stack and only valid within the function but not outside of the function. You get undefined behavior when you access this array.

To return an array like this you should allocate it on the heap, eg. with malloc()

Upvotes: 2

Related Questions