Home > Enterprise >  C code not throwing error for initializing extra string character than it is supposed to be
C code not throwing error for initializing extra string character than it is supposed to be

Time:01-08

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?

CodePudding user response:

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.

  • Related