使用安全功能将字符串添加到C中的字符串 [英] Add string to string in C with safe functions

查看:100
本文介绍了使用安全功能将字符串添加到C中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将文件名复制到字符串中并在其后附加".cpt".但是我无法使用安全功能(strcat_s)来做到这一点.错误:字符串不为null终止!".我确实设置了"\ 0",如何使用安全功能解决此问题?

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);

推荐答案

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

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);

这篇关于使用安全功能将字符串添加到C中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆