Hello,

I'm just started to study malloc and realloc, so i just wrote this program to copy two string from user input and consenterate them. then ofcource print it.

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

int main()
{
    char *str = malloc(3)
    gets(str);

    int sl = strlen(str);

    str = realloc(str, sl);

    strcpy(str, str);

    char *str2 = malloc(2 * sl);

    gets(str2);

    str = strcat(str, str2);

    printf("%s", str);

    free(str);
    free(str2);
    return 0;

   /*char *str = malloc(6);

   strcpy(str, "get");

   str = realloc(str, 10);

   strcat(str, " buck bitch");

   printf("%s", str);

   free(str);*/
}

sometimes it works, sometimes it doesn't and sometimes it works and then crashes. what's wrong?

How long are the strings you enter? If the first string has more than 2 characters, your first call to gets overflows your array. Likewise your second call to gets overflows if the second string entered is 2 * sl characters long or longer.

Either way the call to strcat will overflow str unless str2 is the empty string.

Further the arguments given to strcpy must not overlap, so your call to strcpy always invokes undefined behavior. What is the goal of that call?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.