简体   繁体   中英

Removing an element from a dynamic array

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;
}

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM