I am trying to remove an object from an array of characters that i have dynamically allocated for. But when i check my output for this code I am segfaulting and i dont know why. I am quite new to memory allocation in C. This is just some test code I am writing before I put it into a larger project. Can someone help me debug this?
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
int main(){
int count = 5;
char* test = malloc(count * sizeof(char));
for (int i = 0; i < count; i) {
(test[i]) = 'a';
}
int indexToRemove = 2;
for (int i = 0; i < count; i) {
printf("%s ", &(test)[i]);
}
printf("\n");
char* temp = malloc((count - 1) * sizeof(char)); // allocate an array with a size 1 less han the current one
memmove(temp,test,(indexToRemove 1)*sizeof(char)); // copy everything BEFORE the index
memmove(temp indexToRemove,(test) (indexToRemove 1),(count - indexToRemove)*sizeof(char)); \\copy everything AFTER the index
for (int i = 0; i < count-1; i) {
printf("%s ", &(temp)[i]);
}
printf("\n");
count--;
return 0;
}
CodePudding user response:
You've made two major mistakes. The first is using this:
char** test = malloc(count * sizeof(char*));
instead of this:
char* test = malloc(count * sizeof(char));
There's no reason to use double-indirection here, and it leads to a lot of loose ends and bugs.
The second is here:
free(test);
*test = temp;
You free the space-- and then you write something into it. This is an illegal move which results in undefined behavior which, like any undefined behavior, might work perfectly a thousand times before crashing spectacularly.
EDIT: Here's a version that seems to work:
int count = 5;
char *test = malloc(count * sizeof(char));
test[0] = 'a';
test[1] = 'b';
test[2] = 'c';
test[3] = 'd';
test[4] = 'e';
int indexToRemove = 2;
char* temp = malloc((count - 1) * sizeof(char));
memmove(temp,test,(indexToRemove 1)*sizeof(char));
memmove(temp indexToRemove,(test) (indexToRemove 1),(count - indexToRemove)*sizeof(char));
for (int i = 0; i < count-1; i) {
printf("%c ", temp[i]);
}
printf("\n");
free(test);
return 0;