简体   繁体   中英

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(). 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

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.

But if by chance line points to some valid memory, the program may not crash and it may look as if it works. 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.

Why "smaller than 254" and not 255 ?

Because we need one more char for the zero terminator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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