相关疑难解决方法(0)

为什么要使用strncpy而不是strcpy?

编辑:我添加了示例的源代码.

我遇到了这个例子:

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)

哪个产生了这个输出: …

c buffer-overflow c89 strcpy strncpy

77
推荐指数
5
解决办法
17万
查看次数

为什么strlcpy和strlcat被认为是不安全的?

据我所知,strlcpystrlcat被设计为安全的替代品strncpystrncat.然而,有些人仍然认为他们不安全,只是造成不同类型的问题.

有人可以举例说明如何使用strlcpystrlcat(即一个总是 null终止其字符串的函数)会导致安全问题吗?

Ulrich Drepper和James Antill表示这是事实,但从未提供实例或澄清这一点.

c security strncpy strlcpy

77
推荐指数
6
解决办法
6万
查看次数

如何将char指针复制到char数组中?

所以我有一个指向 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)

我怎样才能做到这一点?

c arrays string pointers

5
推荐指数
1
解决办法
2万
查看次数

指向struct的指针是指向其第一个成员的指针吗?

我正在学习如何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 TypesN1570:

结构类型描述顺序分配的非空成员对象集(并且在某些情况下,是不完整的数组),每个成员对象具有可选地指定的名称并且可能具有不同的类型.

但这里没有任何关于填充的信息.

c struct pointers alignment

4
推荐指数
1
解决办法
145
查看次数

使用c中的free()进行分段错误

我试图用我的一些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)

c memory free segmentation-fault

-1
推荐指数
1
解决办法
809
查看次数