I am making a "simple" print out string, append string and remove section from a string. The append and new string works sometimes, sometimes it outputs nothing. When i do:
char * temp = malloc(newSize);
It just stops outputting anything.
I have commented everything out in sections, trying to find the problem. Can't seem to find the problem, but google keeps coming up with "Heap Corruption".
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char * data;
int length;
} String;
int str_getLength(const char * characters)
{
int index = 0;
while (1)
{
if (characters[index] == '\0') break;
index++;
}
return index;
}
String str_new(const char * characters)
{
String result;
result.length = str_getLength(characters);
result.data = malloc(result.length);
memcpy(result.data, characters, result.length);
return result;
}
void str_append(String * str, const char * characters)
{
int charsLength = str_getLength(characters);
str->data = realloc(str->data, charsLength);
for (int i = 0; i < charsLength; i++) {
str->data[i + str->length] = characters[i];
}
str->length = str->length + charsLength;
}
void str_remove(String * str, int startIndex, int endIndex)
{
if (startIndex < 0 || endIndex > str->length || endIndex < startIndex) {
return;
}
int chunkSize = endIndex - startIndex;
int newSize = str->length - chunkSize;
char * temp = malloc(newSize);
// for (int i = 0; i < str->length; i++)
// {
// if (i < startIndex || i > endIndex) {
// temp[i] = str->data[i];
// }
// }
// free(str->data);
// str->length = newSize;
// str->data = temp;
}
}
int main()
{
String str = str_new("Hello, ");
printf("%s\n", str.data);
str_append(&str, "this is my first C application.");
printf("%s\n", str.data);
str_remove(&str, 0, 3);
printf("%s\n", str.data);
free(str.data);
return 0;
}
I expected it to output a modified string, it doesn't and sometimes it outputs nothing. I am a beginner, sorry if it's a quick fix.