Free() - Program getting aborted.

I am trying to learn C and while trying out some code, the program is getting aborted while I am calling free() .

Here is the code:

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

void print_by_ptr(char **str) {
    printf("<%s>\n",*str);
    printf("Now I am modifying the str.\n");
    *str = "Hello there is modified by the function";
    printf("Printing inside the function\n");
    printf("<%s>\n",*str);
}

int main() {
    char *mystr = malloc(100 * sizeof(char));
    mystr = "Hello There!!";
    print_by_ptr(&mystr);
    printf("Printing in main()\n");
    printf("<%s>\n",mystr);
    //mystr = NULL;
    free(mystr);
    printf("Now exit\n");
    return 0;

}

and here is the output Im getting:

<Hello There!!>
Now I am modifying the str.
Printing inside the function
<Hello there is modified by the function>
Printing in main()
<Hello there is modified by the function>
Aborted
         

Can anyone tell me why is it getting aborted?

char initialization like what you did back there can only be done along with delcaration.

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

void print_by_ptr(char **str) {
    printf("<%s>\n",*str);
    printf("Now I am modifying the str.\n");
    strcpy(*str, "Hello there is modified by the function");
    printf("Printing inside the function\n");
    printf("<%s>\n",*str);
}

int main() {
    char *mystr = malloc(100 * sizeof(char));
    strcpy(mystr, "Hello There!!");
    print_by_ptr(&mystr);
    printf("Printing in main()\n");
    printf("<%s>\n",mystr);
    //mystr = NULL;
    free(mystr);
    printf("Now exit\n");
    return 0;
}

Thanks ahamed101, now it is working fine.

Could you pls explain why that error was coming?

mystr is basically having the address. And when you do mystr = "Hello..."; you are altering the address rather than modifying the content in that address.

1 Like