编辑:我添加了示例的源代码.
我遇到了这个例子:
char source[MAX] = "123456789";
char source1[MAX] = "123456789";
char destination[MAX] = "abcdefg";
char destination1[MAX] = "abcdefg";
char *return_string;
int index = 5;
/* This is how strcpy works */
printf("destination is originally = '%s'\n", destination);
return_string = strcpy(destination, source);
printf("after strcpy, dest becomes '%s'\n\n", destination);
/* This is how strncpy works */
printf( "destination1 is originally = '%s'\n", destination1 );
return_string = strncpy( destination1, source1, index );
printf( "After strncpy, destination1 becomes '%s'\n", destination1 );
Run Code Online (Sandbox Code Playgroud)
哪个产生了这个输出: …
据我所知,strlcpy和strlcat被设计为安全的替代品strncpy和strncat.然而,有些人仍然认为他们不安全,只是造成不同类型的问题.
有人可以举例说明如何使用strlcpy或strlcat(即一个总是 null终止其字符串的函数)会导致安全问题吗?
Ulrich Drepper和James Antill表示这是事实,但从未提供实例或澄清这一点.
所以我有一个指向 char 数组的指针:
temporaryVariable->arrayOfElements; // arrayOfElements is char*
Run Code Online (Sandbox Code Playgroud)
我想复制到我用方括号声明的 char 数组中:
char stringArray[MAXIMUM_LINE_LENGTH + 1];
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
我正在学习如何struct在C中使用s并编写以下示例:
#include <stdio.h>
#include <stdlib.h>
struct s1{
unsigned short member;
};
int main()
{
struct s1 *s1_ptr = malloc(sizeof(*s1_ptr));
s1_ptr -> member = 10;
printf("Member = %d\n", *s1_ptr); // Member = 10
}
Run Code Online (Sandbox Code Playgroud)
问题:在所有情况下,指向结构的指针是否与指向其第一个元素的指针完全相同?
在这个特殊的情况下,它按照我的预期工作,但我不确定它是否有保证.编译器是否可以在一开始就插入一些填充?
唯一我能找到的有关结构类型的布局是Section 6.2.5 Types的N1570:
结构类型描述顺序分配的非空成员对象集(并且在某些情况下,是不完整的数组),每个成员对象具有可选地指定的名称并且可能具有不同的类型.
但这里没有任何关于填充的信息.
我试图用我的一些C代码找到问题.调试器说当我尝试从指针释放mem时发生错误:
int main(int argc, char *argv[]){
char *desc = malloc(30 * sizeof(char));
if(desc == NULL)
{
fprintf(stderr, "Error - cannot allocate memory\n");
}
desc = "Debug this program.";
printf("Description: %s\n", desc);
free(desc);//break point here
int cpid = fork();
....
Run Code Online (Sandbox Code Playgroud)