-2

Why would the following C code not produce a segmetation fault? And what is actually happening in the data locations and pointers?

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

int main (){
    char *str;
    str = (char*) malloc(8);
    strcpy(str, "CM10228");
    printf("String = %s %u\n", str, str);
    strncat(str, " is the best.",12);
    printf("String = %s %u\n", str, str);
    free(str);
    return(0);
}

When would a segmentation fault arise?

Tufty21
  • 15
  • 2
  • Fix the bug and the mystery will go away. – David Schwartz May 26 '22 at 00:19
  • I'm more trying to understand the reason behind this compiling rather than the code itself – Tufty21 May 26 '22 at 00:21
  • 1
    It compiles because it doesn't violate any rule that a compiler is required to catch and your compiler doesn't happen to catch any of the rules that it does violate at compile time. – David Schwartz May 26 '22 at 00:24
  • So would you never get a segmentation fault when writing beyond the allocated memory or does it depend on the compiler? – Tufty21 May 26 '22 at 00:31
  • Segmentation faults are platform-specific things. When and whether you get them depends on details of the platform. – David Schwartz May 26 '22 at 00:32
  • @Tufty21 *So would you never...* If you change `strncat(str, " is the best.",12);` to `memset(str, 0, 10000)`, you'll probably get a segmentation fault (or the equivalent) just about no matter what. – Steve Summit May 26 '22 at 02:02

0 Answers0