4

I want to copy the a file name to a string and append ".cpt" to it. But I am unable to do this with safe functions (strcat_s). Error: "String is not null terminated!". And I did set '\0', how to fix this 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);
  • what about `snprintf()`? – Jack Oct 26 '12 at 18:32
  • It appears your usage is incorrect. I have not used this function but as per [documentation](http://msdn.microsoft.com/en-us/library/d45bbxx4%28v=vs.80%29.aspx) code should be `strcat_s(nieuw, size, ".cpt");` as pointed in [shf301's response](http://stackoverflow.com/a/13092426/925381) – another.anon.coward Oct 26 '12 at 18:37

6 Answers6

11

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

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);
shf301
  • 31,086
  • 2
  • 52
  • 86
  • 2
    +1, Though I have no experience with MS function just curious after reading [documentation of strcpy_s](http://msdn.microsoft.com/en-us/library/td1esda9%28v=vs.80%29.aspx), isn't `nieuw[size] = '\0';` redundant? – another.anon.coward Oct 26 '12 at 18:40
  • Yes it is redundant. `strcpy_s` will always null terminate the string. – shf301 Oct 26 '12 at 19:34
1

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);
Kylo
  • 2,300
  • 1
  • 19
  • 24
1
#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;
}
lovaya
  • 445
  • 3
  • 3
0

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

Check out asprintf. It allows you to print to a string like printf

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

;

lovaya
  • 445
  • 3
  • 3