Home > front end >  Memory Allocation in c with string
Memory Allocation in c with string

Time:09-29

void Strcat(char str1[], char str2[]){
long len1 = strlen(str1);
long len2 = strlen(str2);

char* str = (char*)malloc(((len1   len2)   1)*sizeof(char));
if(str == NULL){
    printf("No memory");
    exit(1);
}
for (int i = 0 ; str1[i] != '\0'; i  ) {
    str[i] = str1[i];
}

str[strlen(str1)] = ' ';
for (long i = 0, j = strlen(str1) 1 ; str2[i] !='\0' ; i  , j  ) {
    str[j] = str2[i];
    if(str2[i 1] == '\0')
        str[j 1] = '\0';
}

//puts(str);
printf("strlen STR -> %ld\n", strlen(str));
for (int i = 0; str[i] != '\0'; i  ) {
    printf("%c",str[i]);
}

free(str);

}

Ok I know the strcat function is a string between two strings. Suppose I put the input "ttt" into the first string And the second string the input "yyy". I am now using dynamic assignment using malloc Now I know we need to take the length of the first second 1 the 1 is for the '\0' character.

So my allocation is size 7.

but I need to make a space between the two strings Do I need my allocation to be 8? because when I do only sizeLength 1 the program is still working and it still puts a space between the two strings and I feel like the compiler forgives me.

CodePudding user response:

I know the strcat function is a string between two strings

Umm, no it isn't? I don't know what that's even supposed to mean. strcat stands for string concatenation (and not "strangle the cat" as one may assume at a glance :) ). Adding a space between them is not how standard library strcat works.

So my allocation is size 7

Yes, that is correct for implementing strcat with input lengths of 3 3, with space for the null terminator at the end.

but I need to make a space between the two strings

Not sure why you'd want to do that, but if you want a space character in between them you need to allocate one extra byte indeed.

Do I need my allocation to be 8?

Only if you need to make room for the space.

because when I do only sizeLength 1 the program is still working

It only works by (bad) luck, this time. What is undefined behavior and how does it work?

I feel like the compiler forgives me

It's not the programmer's job to keep track of correct amounts of memory allocated. C doesn't have bounds-checking of arrays, nor does it have automatic (re)allocation etc as higher level languages might have.

And as someone said in comments, malloc likely allocates larger chunks of aligned memory. Size 8 bytes seems like a very likely candidate for one such aligned chunk, regardless if you actually just use 7 bytes. But this is by no means guaranteed behavior and not something you can rely on.

  • Related