-2

I was running this code to expect an error but to my surprise, it didn't. Even if I initialize a string*(5 bytes)* that is greater than what was allocated using malloc (4bytes).

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

int main() {

        char * name = malloc(4);
        name = "hello";
        
        printf("%s\n",name);
        return 0;


}

This is the output

$ sample.c
$ ./a.out
hello

What might be the underlying details behind this and also why it is not showing segmentation fault as I didn't free the memory?

  • 3
    There is no undefined behaviour - you simply overwrite the pointer with another. The `=` does not copy a string. But anyway, even if you had written past the end of the buffer, failure is not guaranteed. Aside: the string takes 6 bytes not 5. – Weather Vane Jan 07 '23 at 16:11
  • I wonder whether you tried to `free` the buffer before `return`. – AGN Gazer Jan 07 '23 at 16:17
  • @AGNGazer yes I used `free(name)` it executed hello, at last, it showed me `Aborted (core dumped)`. – Vasanthan S R Jan 07 '23 at 16:26
  • The very basic nature of *undefined behaviour* is that it is not defined what will happen. Especially it is not required to trigger some error message. The resulting behaviour may as well look like everything was fine. That is the worst class of errors. It may seem to work fine until it finally bites you when you don't expect it. – Gerhardh Jan 07 '23 at 16:26
  • @Gerhardh Thank you now I understood what undefined error is? – Vasanthan S R Jan 09 '23 at 12:50

1 Answers1

1

This statement doesn't copy hello to name. It changes what name was originally pointing to:

name = "hello";

Now that name points to hello, we have lost all access to the original memory allocated with malloc and there is no way to free it.

There's no undefined behaviour here, but even if there was, the compiler is not required to warn you about it.


"Re: why it is not showing segmentation fault as I didn't free the memory?"


Memory leaks do not raise a segmentation violation signal. It's your job, as a programmer, to manage memory, and avoid any leaks.


"Re: I used free(name) it executed hello, at last, it showed me Aborted (core dumped)."


That's because you're trying to free memory that wasn't allocated with malloc, calloc, aligned_alloc, or realloc. (Why give something that belongs to the data segment or the stack to the heap?)

Only call free with pointers as they are returned by malloc, calloc, aligned_alloc, or realloc.

Aside: A string in C is an array of null-terminated bytes. The string "hello" contains 6 bytes, not 5.

Harith
  • 4,663
  • 1
  • 5
  • 20