lys1030
lys1030

Reputation: 283

Why no segmentation fault when strcpy() causes an buffer overflow?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main() {
    char *a = "aaaaaaaaaaaaaaaa";
    char b[1];
    strcpy(b, a);
    printf("%s\n", b);
}

When running, it prints:

aaaaaaaaaaaaaaaa

If I make *a super long, for example, *a="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", then it will cause a segfault.

Why there is no overflow in the first case?

Upvotes: 0

Views: 600

Answers (3)

Filipe Gon&#231;alves
Filipe Gon&#231;alves

Reputation: 21213

Appearing to work, or, for that matter, not crashing, is a valid form of undefined behavior. Anything can happen when your program has UB. That's why it's highly undesirable.

Upvotes: 0

newfolder
newfolder

Reputation: 108

There is buffer overflow, it doesn't mean it will always couse segmentation fault. It is undefined behaviour - there MAY be segfault. It depends on what is "placed" right after your variable in memory.

Upvotes: 0

Marcus M&#252;ller
Marcus M&#252;ller

Reputation: 36362

A segmentation fault happens when your program tries to access memory that doesn't belong to your program's virtual address space; this will not happen if you just overwrite a bit of stuff right after your original copy destination.

Upvotes: 2

Related Questions