Construire une chaîne en C

Voici le code de démonstration que j’utilise pour construire des chaînes à partir de tableaux de caractères. Existe-t-il un meilleur moyen de construire Ssortingng *RV200# *FV200# ??

 int main() { char Ssortingng4H1[10] = "*FV"; char Ssortingng4H3[10] = "*RV"; char Ssortingng4H2[10] = "#"; char data1[10]; char data2[10]; snprintf(data1,4, "%03d", 200); //Convert integer to ssortingng function snprintf(data2,4, "%03d", 200); //Convert integer to ssortingng function ConvertToSsortingng(Ssortingng4H1,data1, 3); //*FV200 ConvertToSsortingng(Ssortingng4H3,data2, 3); //*RV200 ConvertToSsortingng(Ssortingng4H1,Ssortingng4H2,6); //*FV200# ConvertToSsortingng(Ssortingng4H3,Ssortingng4H2,6); //*RV200# //Display Ssortingng4H1 And Ssortingng 4H3 } void ConvertToSsortingng(char subject[], const char insert[], int pos) { char buf[100] = {}; strncpy(buf, subject, pos); // copy at most first pos characters int len = strlen(buf); strcpy(buf+len, insert); // copy all of insert[] at the end len += strlen(insert); // increase the length by length of insert[] strcpy(buf+len, subject+pos); // copy the rest strcpy(subject, buf); // copy it back to subject // deallocate buf[] here, if used malloc() } 

Le nombre 200 n’est pas connu au début du programme, il est extrait de la mémoire à l’aide de la fonction IDE pour obtenir la valeur d’une adresse mémoire particulière. comme ça :-

 unsigned short BUF = GetWord(@FrontVIB@,0); unsigned short BUF1 = GetWord(@RearVIB@,0); //BUF and BUF1 stores the value of address @FrontVIB@ and @RearVIB@ respectively **structure** :- unsigned short GetWord( @Address Alias@, Address Offset ); 

C’est un exemple simple. Je vais probablement avoir le vote négatif 🙂

 #include  #include  #include  #include  bool concatenateSsortingng(char **dest, size_t *size, char *ssortingngToAdd) { bool retVal = true; char *dest_old = *dest; *size += strlen(ssortingngToAdd); if (*dest == NULL) { *size += 1; // to add null terminator of ssortingng *dest = calloc(1, size); } else { *dest = realloc(*dest, size); } if (dest == NULL) { free(dest_old); retVal = false; } else { strcat(*dest, ssortingngToAdd); } return retVal; } int main() { char newSsortingng[32] = {0}; int number; size_t size = 0; char *data1 = NULL; printf("Insert a ssortingng:"); scanf(" %s", newSsortingng); if (concatenateSsortingng(&data1, &size, newSsortingng)) { printf("Insert a number:"); scanf(" %d", &number); sprintf(newSsortingng, "%03d", number); if (concatenateSsortingng(&data1, &size, newSsortingng) ) { printf("Insert a ssortingng:"); scanf(" %s", newSsortingng); if (concatenateSsortingng(&data1, &size, newSsortingng)) printf("%s\n", data1); } } free(data1); } 

Sans utiliser l’allocation dynamic

 #include  #include  #include  #include  bool concatenateSsortingng(char *dest, size_t size_of_dest, char *ssortingngToAdd) { bool retVal = true; size_t new_size = strlen(dest) + strlen(ssortingngToAdd); if (new_size < size_of_dest) { strcat(dest, stringToAdd); } else { retVal = false; } return retVal; } int main() { char result[128] = {0}; char newString[32] = {0}; int number; printf("Insert a string:"); scanf(" %s", newString); printf("%s\n", newString); if (concatenateString(result, sizeof(result), newString)) { printf("Insert a number:"); scanf(" %d", &number); sprintf(newString, "%03d", number); if (concatenateString(result, sizeof(result), newString) ) { printf("Insert a string:"); scanf(" %s", newString); if (concatenateString(result, sizeof(result), newString)) printf("%s\n", result); } } } 

CONTRIBUTION

 Insert a ssortingng: *RV Insert a number: 200 Insert a ssortingng: # 

SORTIE

 *RV200# 

Un certain nombre de problèmes, je ne m’attaque qu’à ConvertToSsortingng()


Bien que certaines tentatives aient été faites pour résoudre les problèmes de mémoire tampon de chaîne, le code de l’OP contient trop de trous. Considérer ce qui suit.

 void ConvertToSsortingng(char subject[], const char insert[], int pos) { char buf[100] = {}; strncpy(buf, subject, pos); // copy at most first pos characters int len = strlen(buf); ... 

Quel est l’impact de pos == 100 ?
strlen(buf) peut tenter de trouver la longueur d’un tableau de caractères sans caractère null -> UB.

Quel est l’impact de pos > 100 ?
strncpy() tente d’écrire des données en dehors des liens de buf .

Pedantic: Quel est l’impact de pos < 0 ?
strncpy() tente d'écrire des données en dehors des liens de buf car pos est converti en un nombre non signé excessif.


Concernant la strcpy(buf+len, subject+pos);

Quel est l'impact si pos dépasse strlen(subject)
UB as code essaie de lire le subject extérieur.


Tentative de réécriture. Les éléments clés: inclure la taille disponible pour le subject développé sont passés et déterminent les longueurs de chaîne. Puis testez l'acceptabilité. Après tout cela, déplacez la fin du subject pour faire de la place pour l' insert .

 void ConvertToSsortingng(char subject[], size_t subject_size, const char *insert, size_t pos) { size_t insert_length = strlen(insert); size_t subject_length = strlen(subject); // Insure pos does not exceed subject_length, // this critical part missing in OP code if (pos > subject_length) { pos = subject_length; } // Insure we have enough space size_t buf_size = subject_length + insert_length + 1; if (buf_size > subject_size) { Handle_Insufficent_subject_size(); return; } // Move end portion of `subject` over to the right `insert_length` places. memmove(subject + pos + insert_length, subject + pos, subject_length - pos + 1); memcpy(subject + pos, insert, insert_length); // copy insert }