-4

I have run the below program:

#include<stdio.h>
#include<string.h>
#include<malloc.h>
int main()
{
    char *p, *q;
    p = (char*)malloc(1);
    q = (char*)malloc(25);
    strcpy(p, "abcd");
    strcpy(q,"efgh");
    strcat(p,q);
    printf("%s",p);
    return 0;
}

I was expecting that it will give error "segmentation fault". But instead it printed the output as:

abcdefgh

I don't know how does it work because p is assigned only 1 byte and we are copying a string which takes more space. Is it the right behavior?

OS: windows 7
Compiler: mingw C compiler
Sarwan
  • 595
  • 3
  • 8
  • 21
  • 7
    It's called Undefined Behavior... – Abhineet Oct 14 '14 at 10:00
  • 1
    With a longer string it *does* crash. – Jongware Oct 14 '14 at 10:04
  • Writing over the boundaries of an array does not have to result in a segmentation fault. Many things can happen, and that is why it is undefined behaviour. Probably your `malloc` results in a block large enough to contain `"abcd"` plus terminating zero and that is why it works. But that is not guaranteed. It is, as said, undefined behaviour. – Rudy Velthuis Oct 14 '14 at 10:04
  • @Jongware: not necessarily. It may cause heap corruption, but if initial heap is large enough, it does not have to crash. Often, writing over memory that belongs to a process does not result in a crash, only in corruption. – Rudy Velthuis Oct 14 '14 at 10:07
  • @Rudy: you may be right. Unfortunately I got that worthless Windows "Checking for a solution.." dialog pop up, which does not state what the exact error is ... (It also never seems to *find* a solution.) – Jongware Oct 14 '14 at 10:12
  • Quite often when overwriting memory, the problems show up in an entirely different place or at a much later time. A subsequent call to `free()` or `malloc()` might cause a "segmentation fault" if `strcpy()` has overwritten the internal structures used by those functions. – Nisse Engström Oct 14 '14 at 17:38

1 Answers1

-1

When you allocate 1 byte of memory using malloc, what malloc actually does is that it request for about 134k bytes of memory from the kernel and gives 1 byte to the variable and keeps rest for future use as a reserve, this way when you do an malloc next time the you will get address from this from the reserve. And all the address in the reserve are valid so you won't be getting any segfault. If you check the address of p and q , you will get understand why it is printing so.

jsaji
  • 900
  • 1
  • 15
  • 31
  • What it actually does depends on the platform, the memory manager used, etc.etc. What you describe, or something similar, is probably what happened here, but it is just undefined behaviour. A segfault is just one of the possible consequences. – Rudy Velthuis Oct 14 '14 at 12:25