4

我想将一个文件名复制到一个字符串并将“.cpt”附加到它。但是我无法使用安全功能(strcat_s)来做到这一点。错误:“字符串不是空终止的!”。我确实设置了'\0',如何使用安全功能解决这个问题?

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

6 回答 6

11

_s 函数的size参数是目标缓冲区的大小,而不是源缓冲区。该错误是因为第一个字符中没有空终止nieuw符。试试这个:

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);
于 2012-10-26T18:29:39.657 回答
1

也许一些标准解决方案?

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);
于 2012-10-26T18:47:27.600 回答
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;
}
于 2012-10-26T18:48:04.660 回答
0

为什么不

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';
于 2012-10-26T18:27:09.953 回答
0

退房asprintf。它允许您打印到像 printf 这样的字符串

于 2012-10-26T18:27:53.577 回答
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)

;

于 2012-10-26T18:33:58.623 回答