Add string to string in C with safe functions

I want to copy the file name to a string and add ".cpt" to it. But I can not do this with safe functions (strcat_s). Error: "The line is not terminated by zero!". And I set '\ 0', how to fix it using safe functions?

size = strlen(locatie); size++; nieuw = (char*)malloc(size+4); strcpy_s(nieuw, size, locatie); nieuw[size] = '\0'; strcat_s(nieuw, 4, ".cpt"); // <-- crash puts(nieuw); 
+4
source share
6 answers

The size parameter of _s functions is the size of the destination buffer, not the source. The error is that in the nieuw character there is no null terminator in the first for characters. Try the following:

 size = strlen(locatie); size++; int nieuwSize = size + 4; nieuw = (char*)malloc(nieuwSize ); strcpy_s(nieuw, nieuwSize, locatie); nieuw[size] = '\0'; strcat_s(nieuw, nieuwSize, ".cpt"); // <-- crash puts(nieuw); 
+7
source

Why not

 size = strlen(locatie); size++; nieuw = (char*)malloc(size+6); strcpy_s(nieuw, size, locatie); strcat_s(nieuw, 4, ".cpt"); puts(nieuw); nieuw[size + 5] = '\0'; 
0
source

Check out asprintf . It allows you to print on a line such as printf

0
source
 size = strlen(locatie); size++; nieuw = (char*)malloc(size+4); strcpy_s(nieuw, size, locatie); nieuw[size] = '\0'; strcat_s(nieuw, size, ".cpt"); puts(nieuw) 

;

0
source

Maybe some standard solution?

 const char * const SUFFIX = ".cpt"; size = strlen(locatie) + strlen(SUFFIX) + 1; // +1 for NULL nieuw = (char*)malloc(size); snprintf(nieuw, size, "%s%s", locatie, SUFFIX); 
0
source
 #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char old[] = "hello"; size_t size = strlen(old) + 5;; char *new_name = (char*)malloc(size); new_name[size-1] = '\0'; strcpy_s(new_name, size, old); strcat_s(new_name, size, ".cpp"); printf("%s\n", new_name); return 0; } 
0
source

Source: https://habr.com/ru/post/1442382/


All Articles