I am trying to write a function called "function", that thakes two strings, named "string1" and "string2" as input and returns another string, named "string" as output. I use the malloc method to generate "string", it does what I expect, but when I later use "free" on "string" I get some error. (Below you find a working example that produces this error.) Could you please explain to me what I am doing wrong.
#include <stdio.h>
#include <stdlib.h>
#define LENGTH_STRING(x) ((sizeof(x)/sizeof((x)[0]))-1)
char* function(char* string1, int string1_length, char* string2, int string2_length)
{
char* string = (char*) malloc((string1_length+string2_length+1)*sizeof(char));
if (!string)
{
printf("Memory could not be allocated. \n");
return NULL;
}
for (int i = 0; i < string1_length+string2_length+1; i = i + 1)
string[i] = 'A';
string[-1] = '\0';
return string;
}
int main()
{
char string1[] = "ABC";
char string2[] = "XYZ";
int length_string1 = LENGTH_STRING(string1);
int length_string2 = LENGTH_STRING(string2);
char* string = function(string1, length_string1, string2, length_string2);
printf("%s \n", string); // I get till here.
free(string);
printf("Do I get through here?"); // This does not get printed.
return 0;
}
>Solution :
As per comments, you can’t subscript with a negative number, unlike languages like Python.
If you want to fill a string with 'A' characters in C, you’d want to iterate from 0 to the length of the string minus two to leave space for the null terminating character.
for (int i = 0; i < buffer_length - 2; i++) {
string[i] = 'A';
}
string[buffer_length - 1] = '\0';
You might also not locally scope i to the loop, and then use it after the loop to set the null terminator, as then it will have been incremented to point to the end of the buffer.
int i;
for (i = 0; i < buffer_length - 2; i++) {
string[i] = 'A';
}
string[i] = '\0';