Return malloc to pointer does not stay between functions

Asked

Viewed 84 times

0

I have these two examples here:

example 1:

void copiaStr(char *a,char *b){
    b = (char *) malloc(strlen(a));
    for(int i = 0; i < strlen(a) ;i++){
        b[i] = a[i];
    }
}


int main(){
    char *a = "alou";
    char *b;

    printf("%s\n",a);
    copiaStr(a,b);
    printf("%s\n",b);
}

example 2:

void copiaStr(char *a,char *b){
    for(int i = 0; i < strlen(a) ;i++){
        b[i] = a[i];
    }
}


int main(){
    char *a = "alou";
    char *b = (char *) malloc(strlen(a));

    printf("%s\n",a);
    copiaStr(a,b);
    printf("%s\n",b);
}

The first example does not work, gives segmentation error, as if the address allocated within the method, and assigned to b, did not continue after the end of the method, but I passed b as a pointer, I thought it would be a value pass per reference, why is this error occurring? And how to make b take the value of malloc() from within the method?

The example is simple, but I think I’m having the same problem when I write list manipulation methods.

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

3

Exactly, you went through b as a pointer, only b is already a pointer, so you are passing the value of b of main() for the parameter b function. You can manipulate the contents of this pointer, but you cannot manipulate the contents of b which remains a normal value and not a reference. If you want to be able to change the value of b you have to spend your own b as a reference:

void copiaStr(char *a, char **b) {
    *b = malloc(strlen(a));
    for (int i = 0; i < strlen(a); i++) *(b[i]) = a[i];
}

int main() {
    char *a = "alou";
    char *b;
    printf("%s\n", a);
    copiaStr(a, &b);
    printf("%s\n", b);
}

I put in the Github for future reference.

Although this will work the ideal is the other code, you allocate and pass the buffer allocated, should not allocate within the function. Even in both have an error because it does not release the memory. For a simple example does not cause problem, but is wrong.

Has more problems. Should not use strlen(). And the most correct is to pass the known size of string, even for safety, in addition to performance. The ideal would be to use a strcpy() and not do at hand, may even have optimizations in it and done more robustly. Done this its function ends up being unnecessary.

  • Yes, it is completely unnecessary for practical terms, but the only purpose is the study. Thank you very much for the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.