简体   繁体   English

strcpy 上的分段

[英]SEGFAULT on strcpy

i have a function that starts as我有一个开始的功能

void findErrors(int lineIndex){
  char *line;
  strcpy(line, lines[lineIndex]);

then calls another functions that starts as然后调用另一个启动为的函数

void fixErrors(int lineIndex, char *word){
  char *line;
  strcpy(line, lines[lineIndex]);

the first function works but i get a segfault when it calls the second function.第一个函数有效,但在调用第二个函数时出现段错误。 lineIndex is the same for both words and findErrors does not call the lines array except in strcpy(). lineIndex 对于这两个词是相同的,除了在 strcpy() 中之外,findErrors 不会调用 lines 数组。 Why is this happening?为什么会这样? is this a bad way to use the function and i'm simply getting lucky on the first function?这是使用该功能的糟糕方式吗,我只是在第一个功能上很幸运? The problem goes away if I change the line in fixErrors from如果我将 fixErrors 中的行从

char *line;

to

char line[255];

but i'd rather not have a possibility of another segfault on a huge line.但我宁愿没有在一条巨大的线上出现另一个段错误的可能性。 i guess i could also我想我也可以

char *line = malloc(strlen(lines[lineIndex])+1)

but i'm really curios why the first way doesn't work.但我真的很好奇为什么第一种方法不起作用。

void findErrors(int lineIndex){
  char *line;
  strcpy(line, lines[lineIndex]);
//^ this is undefined behaviour.

At that point line is not initialized and strcopying something to a non initialized pointer results in undefined behaviour, usually a segfault.在这一点上, line未初始化,将某些内容复制到未初始化的指针会导致未定义的行为,通常是段错误。

But if by chance line points to some valid memory, the program may not crash and it may look as if it works.但是,如果偶然line指向某个有效内存,则程序可能不会崩溃,并且看起来好像可以正常工作。 It's undefined behaviour.这是未定义的行为。

Case where it works:工作情况:

void findErrors(int lineIndex){
  char line[255];
  strcpy(line, lines[lineIndex]);

Here line points to a buffer of length 255. You can strcpy to this buffer without problems as long as the length of the source string is smaller than 254.这里line指向一个长度为 255 的缓冲区。 只要源字符串的长度小于 254,你就可以毫无问题地strcpy到这个缓冲区。

Why "smaller than 254" and not 255 ?为什么“小于 254”而不是 255 ?

Because we need one more char for the zero terminator.因为我们还需要一个字符作为零终止符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM