Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

How to increase the size of dynamic memory for a string (reallocate) in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#define SIZE 13
 
int main(void)
{
    // The pointer *s allocated on the stack
    // The dynamic memory is allocated on the heap
    char *s = (char *)malloc(SIZE * sizeof(char));
    
    if (s == NULL)
    {
        perror("realloc() error");
        return -1;
    } 
    
    printf("s = %s (after malloc)\n", s);
    strcpy(s, "c c++");
    printf("s = %s (after strcpy)\n", s);
    printf("s address = %p\n", s);
    
    {
        char *tmp = realloc(s, SIZE + 10);
 
        if (tmp == NULL)
        {
            perror("realloc() error");
            free(s); 
            return -1;
        }      
 
        s = tmp;
    }
     
    printf("s = %s (after realloc)\n", s);
    strcat(s, " java");
    printf("s = %s (after strcat)\n", s);
    printf("s address = %p\n", s);
 
    free(s);
 
    return 0;
}
 
   
/*
run:
     
s =  (after malloc)
s = c c++ (after strcpy)
s address = 0000000000755730
s = c c++ (after realloc)
s = c c++ java (after strcat)
s address = 0000000000755730
 
*/

 



answered Jun 20, 2017 by avibootz
edited Jul 27, 2017 by avibootz

Related questions

1 answer 185 views
2 answers 203 views
203 views asked Jul 27, 2017 by avibootz
1 answer 134 views
2 answers 143 views
1 answer 235 views
1 answer 104 views
104 views asked Nov 30, 2023 by avibootz
...