-2

I would like to understand why this piece of code will not crash :

#include<studio.h>
#include<string.h>
main()
{
    char *a;
    a=(char *)malloc(1);
    strcpy(a, "example");
}

I though we are writing to memory that is not the processes' since we allocate only 1 byte for the char * and we write more than that.

Can somebody please explain?

Thanks in advance.

alk
  • 69,737
  • 10
  • 105
  • 255
quickdraw
  • 247
  • 1
  • 2
  • 12
  • 4
    It doesn't crash because the code causes *undefined behavior*. That can mean anything happening, including "work". – PaulMcKenzie Jul 17 '16 at 06:09
  • 1
    u wrote `#include` in your code.u should write `#include`. – asad_hussain Jul 17 '16 at 06:10
  • The code misses to prototype `malloc()`, which causes UB if `sizeof (void*)` is different from `sizeof (int)`. – alk Jul 17 '16 at 07:12
  • @a874: Your edit significant changed the question after comments and answers had been given. This made some of them un-understandable, that why I just rolled back your edit. – alk Jul 21 '16 at 13:34

2 Answers2

3

Allocate enough space for the string.

#include <stdio.h>
#include <string.h>
int main()
{
    char * a;
    a = (char *)malloc(32);
    strcpy(a, "example");
    free(a); // don't forget to free
}

Explanation:

  • You allocated 1 byte you copied 7+1 (example + '\0').
  • You tried to access memory that was not allocated.

Read articles about buffer overflow.

Important:

If you are not aware of the input size (now we know "example" is 7+1 bytes) you should use strncpy to specify the maximum number of bytes that can be copied.

There is a function strdup that duplicates the string. Same as allocation + strcpy.

Szabolcs Dombi
  • 5,493
  • 3
  • 39
  • 71
  • The code misses to prototype `malloc()`, which causes UB if `sizeof (void*)` is different from `sizeof (int)`. – alk Jul 17 '16 at 07:13
  • working on 64 and 32 bit as well `sizeof(char *) = sizeof(void *)` – Szabolcs Dombi Jul 17 '16 at 07:24
  • If the prototype to `malloc()` is missing `malloc()` is taken to return an `int` not a `char*`. The cast to `char*` would be applied to the `int` returned, which already lacks significant bits, typically 32. That's one of the reasons why in C `malloc()` should not be casted. – alk Jul 17 '16 at 07:27
  • my `malloc.h` contains this: `void *__cdecl malloc(size_t _Size);` – Szabolcs Dombi Jul 17 '16 at 09:53
  • But you do not include it, not indirectly via the standard `stdlib.h` nor directly. – alk Jul 18 '16 at 09:57
  • No more malloc defined in * – Szabolcs Dombi Jul 18 '16 at 10:57
2

Your allocator may allocate small chunks of fixed size for requests below certain threshold. I wouldn't be surprised you've got 8 bytes back, so strcpy works without crash

Severin Pappadeux
  • 18,636
  • 3
  • 38
  • 64