Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
636 views
in Technique[技术] by (71.8m points)

c - Segmentation fault around strcpy?

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

Why does it make Segmentation fault

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

when this doesn't

char *cmd;
cmd = "plop";

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

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.

Thanks !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you do:

char * cmd;

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

Then, when you do this:

strcpy(cmd, argv[0]);

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.

When you do this:

cmd = "plop";

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

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++

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...