周围的strcpy分割的错吗? [英] Segmentation fault around strcpy?

查看:134
本文介绍了周围的strcpy分割的错吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道你会说唱我在指关节,但

I know that you will rap me over the knuckles but.

为什么它使分段故障

char* cmd;
strcpy(cmd, argv[0]);

在这不

char *cmd;
cmd = "plop";

我没有,因为一会儿练了,不记得为什么。

I didn't practice since a while, and can't remember why.

PS:其实,我知道,这样的事情,在之前strcpy的,效果会更好。

ps: actually, i know that something like that, before the strcpy, would be better

char *cmd = (char*) malloc(strlen(argv[0]));

但我只是想知道为什么这个分段错误。

but i'm just wondering why this segmentation fault.

谢谢!

推荐答案

当你这样做:

char * cmd;

你分配一个指针的堆栈的。此指针不初始化为任何有意义的值。

You're allocating a pointer on the stack. This pointer is not initialized to any meaningful value.

然后,当你这样做:

strcpy(cmd, argv[0]);

您复制包含在字符串的argv [0] 来指向的地址 CMD ,这是.. 。一些毫无意义。既然你是幸运的,它只是出现segfaults。

You copy the string contained in argv[0] to the address pointed to cmd, which is... something meaningless. Since you're lucky, it simply segfaults.

当你这样做:

cmd = "plop";

您分配给 CMD 地址静态分配的字符串常量。因为这样的字符串是只读的,写上他们的是未定义的行为。

You assign to cmd the address to a statically allocated string constant. Since such strings are read only, writing on them is undefined behavior.

那么,如何解决这个问题?分配内存运行时写入。有两种方法:

So, how to solve this? Allocate memory for the runtime to write to. There's two ways:

第一种是将栈上分配数据,如下所示:

The first one is to allocate data on the stack, like this:

char cmd[100]; // for instance

该分配的100 字符 S中的堆栈上的数组。然而,这并不一定是强大的,因为你必须事先知道你会需要多少内存。栈也比堆小。我们哪会导致选项号2:

This allocates an array of 100 chars on the stack. However, it's not necessarily robust, because you must know in advance how much memory you'll need. The stack is also smaller than the heap. Which leads us to option number 2:

char *cmd = malloc(whatever_you_need); // no need to cast, by the way, unless you're in C++

本中分配 whatever_you_need 字符 S于堆上。不要忘了释放与免费内存一旦你用它做。

This allocates whatever_you_need chars on the heap. Don't forget to release the memory with free once you're done with it.

这篇关于周围的strcpy分割的错吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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