strcpy 周围的分段错误? [英] Segmentation fault around strcpy?

查看:13
本文介绍了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所指向的地址,这是……毫无意义的东西.既然你很幸运,它只是段错误.

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 个 char 的数组.但是,它不一定是健壮的,因为您必须事先知道您需要多少内存.栈也比堆小.这将我们引向选项 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 char.完成后不要忘记使用 free 释放内存.

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天全站免登陆