How to resize a string with realloc() in C

1 Answer

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

// Function to allocate memory and initialize the string
char* allocateString(size_t size, const char *initialValue) {
    char *str = malloc(size * sizeof(char));
    if (str == NULL) {
        perror("Failed to allocate memory");
        return NULL;
    }
    strcpy(str, initialValue);
    
    return str;
}

// Function to resize and append content to a string
char* resizeAndAppend(char *str, const char *append) {
    size_t newSize = strlen(str) + strlen(append) + 1;
    
    char *temp = realloc(str, newSize * sizeof(char));
    if (temp == NULL) {
        perror("Failed to reallocate memory");
        free(str); // Clean up original memory
        return NULL;
    }
    str = temp;
    strcat(str, append);
    
    return str;
}

int main() {
    // Use the function to allocate and initialize
    char *str = allocateString(6, "Hello");
    if (str == NULL) return 1;

    // Resize and append more text
    str = resizeAndAppend(str, " C Programming");
    if (str == NULL) return 1;

    printf("Resized string: %s\n", str);

    // Free memory
    free(str);

    return 0;
}



/*
run:

Resized string: Hello C Programming

*/

 



answered Jul 19, 2025 by avibootz

Related questions

2 answers 195 views
1 answer 225 views
225 views asked May 19, 2025 by avibootz
2 answers 219 views
1 answer 83 views
2 answers 357 views
...