Search code examples
csplitpass-by-referencedynamic-memory-allocationc-strings

Issues reallocating memory to string


New to c and trying to learn. Here I tried to create a function that copies a string until first space using dynamic memory allocation and byref. Seems like I'm doing something wrong with the way I used realloc. Can you help me figure out what is wrong with the way I used dynamic memory allocation?

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

void f1(char **c, char *s);

int main() {
    char * s = "this is an example";
    char *c;

    c =(char *) malloc(sizeof(char));
    f1(&c,s);
    free(c);
}

void f1(char **c, char *s)
{
    int i=0;
    while ((s[i])!=' ')
    {
        (*c)[i]=s[i];
        i++;
        (*c)=(char *)realloc ((*c),sizeof(char)*i);
    }

    (*c)[i]='\0';
    printf("\n%s\n",*c);

}

Solution

  • void f1(char** r, char* s) 
    {
       // find size of new buffer
       size_t len = 0;
       while(s[len] != '\0' && s[len] != ' ') len++;
    
       *r = (char*)malloc(len + 1);
    
        memcpy(*r, s, len);
    
        (*r)[len] = '\0';
    }