0

I'm having some issues with realloc, for example, this code

    char *s = (char*)malloc(sizeof(char)*17);
    s = "bruhbruhlmaolmao";
    s = (char*)realloc(s, sizeof(char)*18);
    if(s == NULL) printf("Memory allocation failed");
    else printf("%s\n",s);

I'm trying to reallocate the memory chunk that s is pointing at to a larger memory location in the heap.

I've compiled it and the compiler returns no warning. When I run the executable, It prints out nothing. I hope you can explain to me why and how to fix it

3
  • 3
    s = "bruhbruhlmaolmao"; "throws away" the memory you just allocated and instead points the pointer at a string literal. And you cannot realloc a string literal Commented Mar 12, 2022 at 17:47
  • 1
    C doesn't let you copy an array with a single assignment statement. You can use a loop or one of the functions in string.h. Commented Mar 12, 2022 at 17:55
  • 3
    s = "bruhbruhlmaolmao"; should be strcpy(s, "bruhbruhlmaolmao"); Commented Mar 12, 2022 at 17:57

1 Answer 1

1

Well, apparently I made a dumb decision by assigning s to a string: s = "bruhbruhlmaolmao";, what I should really do is use something in string.h library like strcpy

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.