I have a dynamic array of strings, for example "123", "231" etc. Next I need to delete a particular array string. For the deletion I used the normal technique used for static arrays, that is to move all the elements to the left by one position, in order to overwrite the deleted element. But since the array is dynamic, how do I fix the memory? That is, to decrement the memory this array is using? Here is my code: PART OF CODE TO INSERT A STRING:
char **received_messages;
if(array_size == 0){
debug_level == 2 && printf("First message received..\n");
received_messages = malloc(sizeof(char*));
received_messages[0] = malloc((1024+1) * sizeof(char));
array_size = array_size + 1;
strcpy(received_messages[0],id);
}
else{
for(int i=0; i<array_size; i++){
debug_level == 2 && printf("Compare between %s and %s\n", received_messages[i],id);
if( (strcmp(received_messages[i],id)) == 0){
id_found= 1;
}
}
if(id_found== 1){
debug_level == 2 && printf("ID found.\n");
}else{
debug_level == 2 && printf("ID not found.\n");
received_messages[array_size] = malloc((1024+1) * sizeof(char));
strcpy(received_messages[array_size],id);
array_size = array_size + 1;
}
}
PART OF CODE TO DELETE A STRING:
for(int j=0; j<array_size;j++){
printf("I'm searching the SN to delete. Compare %s to %s\n", received_messages[j], id_to_delete);
if(strstr(received_messages[j], id_to_delete) != NULL){
printf("Sequence number found. It is %s\n", id_to_delete);
for(int k=j; k<array_size; k++){
received_messages[k] = received_messages[k+1];
array_size = array_size -1;
}
}
}
printf("Now, the array has %d elements. Actually valid sequence number are: \n", array_size);
if(array_size > 0){
for(int j=0; j<array_size; j++){
printf("%d) %s\n", j+1, received_messages[j]);
}
}else{
printf("Actually no valid sequence number.\n");
}
freethe memory have allocated for it.received_messagesitself when you increase its size. That means for any index except0you will go out of bounds and have undefined behavior.received_messagesarray, callfree(received_messages[j])