0

Can I Reallocate memory using other function ??

Can I Reallocate memory using other function in which memory is not allocated using malloc ?? Does this program will work fine ?? (It is not working properly in CxxDroid. After Reallocation I'm getting empty string. But after Reallocation in main function I'm getting correct result.) But working in sololearn https://code.sololearn.com/cGkqqGgnuvn4/?ref=app

6th Jul 2021, 6:24 PM
🌀 Shail Murtaza شعیل مرتضیٰ
🌀 Shail Murtaza شعیل مرتضیٰ - avatar
6 Answers
+ 2
Jazz Oh! Yes! You are right. I didn't noticed that string is now a local variable of rem function. 😅😅 Thank you! Can you please tell me what is "char **string"
7th Jul 2021, 8:20 AM
🌀 Shail Murtaza شعیل مرتضیٰ
🌀 Shail Murtaza شعیل مرتضیٰ - avatar
+ 1
🌀 Shail Murtaza شعیل مرتضیٰ Here's a possible solution: #include <stdio.h> #include <stdlib.h> #include <string.h> void rem(char **ptr); int main() { char *str = malloc(50); strcpy(str, "Programmingm"); puts(str); rem(&str); puts(str); } void rem(char **ptr) { int len = strlen(*ptr); (*ptr)[len - 1] = 0; if (!(ptr = realloc(*ptr, len + 1))) puts("Reallocation Failed"); } // Hope this helps
8th Jul 2021, 11:57 AM
Calvin Thomas
Calvin Thomas - avatar
0
Why I'm getting segmentation Fault. I guess returning new address is better choice. https://code.sololearn.com/cYoVSb6w4ItH/?ref=app
7th Jul 2021, 8:27 AM
🌀 Shail Murtaza شعیل مرتضیٰ
🌀 Shail Murtaza شعیل مرتضیٰ - avatar