本文介绍了同时采用的strcpy(分段错误)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个全球性的结构:

I have a global structure:

struct thread_data{
   char *incall[10];
   int syscall arg_no;
   int client_socket;
};

和在main()

char buffer[256];
char *incall[10];
struct thread_data arg_to_thread;

strcpy(incall[0],buffer);   /*works fine*/
strcpy(arg_to_thread.incall[0],buffer); /*causes segmentation fault*/

为什么会出现这种情况,请出建议的方式。

Why does this happen and Please suggest a way out.

感谢

推荐答案

一个内存设计缺陷意味着什么是错的。但是的没有的段错误并不意味着事情的不是的错误。如果两种情况基本相同,一个设计缺陷,另一个没有,这通常意味着他们的两个的错,但只有其中一人恰好是触发段错误。

A segfault means that something is wrong. But no segfault does not mean that something isn't wrong. If two situations are basically the same, and one segfaults and the other does not, it usually means that they are both wrong, but only one of them happens to be triggering the segfault.

纵观行的char *门店[10] ,这是什么意思是你有10个指针的数组为char。默认情况下,这些指针将在随机的地方被人指指点点。因此,strcpying到门店[0]将复制该字符串的随机位置。这是最有可能会出现段错误!您需要[0]首先初始化门店(使用的malloc )。

Looking at the line char* incall[10], what that means is you have an array of 10 pointers to a char. By default, these pointers will be pointing at random places. Therefore, strcpying into incall[0] will be copying the string to a random location. This is most likely going to segfault! You need to initialise incall[0] first (using malloc).

因此​​,一个更大的问题是,为什么的的第一行段错误?我猜想的原因是它的恰好的,无论是内存之前是一个有效的指针。因此,strcpy的不段错误,它只是覆盖别的东西,这将导致后面完全出乎意料的行为。所以,你必须修复的两个的code线。

So a bigger question is why doesn't the first line segfault? I would imagine the reason is that it just so happens that whatever was in memory before was a valid pointer. Therefore, the strcpy doesn't segfault, it just overwrites something else which will later cause completely unexpected behaviour. So you must fix both lines of code.

另一个问题(一旦你有固定的)是的strcpy 本身是非常危险的 - 因为它拷贝字符串,直到找到一个0字节,然后停止,你可以永远不能确定它到底有多少要复制(除非你使用的strlen 来分配目标内存)。所以,你应该用函数strncpy 来代替,以限制复制到缓冲区的大小,字节数。

Another issue (once you have fixed that) is that strcpy itself is highly dangerous -- since it copies strings until it finds a 0 byte and then stops, you can never be sure exactly how much it's going to copy (unless you use strlen to allocate the destination memory). So you should use strncpy instead, to limit the number of bytes copied to the size of the buffer.

这篇关于同时采用的strcpy(分段错误)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 09:10