0

New to C here. Was trying out strcat and thought my code should give error but it works fine.

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

int main(int argc, char* argv[]){
    char string[] = "string!";
    char* concat = (char*)malloc(sizeof(char));
    strcat(concat,string);
    printf("%s\n", concat);
    free(concat);
}

As a matter of fact, I am able to access memory like printf("%c\n", *(concat +1232)); which should throw error, right?

I was trying out string functions and seeing doing what will give me what errors. I thought that the above code would have given error but it doesn't. Is my understanding of strcat wrong?

Cardinal
  • 73
  • 5
  • 1
    Undefined behaviour is undefined. You should not expect anything. – Cheatah Oct 27 '22 at 11:56
  • 1
    Any decent learning resource should have taught you that C doesn't have any kind of bounds-checking. Going out of bounds leads to *undefined behavior*. And it's your responsibility as the programmer to make sure that your program doesn't go out of bounds. – Some programmer dude Oct 27 '22 at 11:57
  • You would get a segment fault only if you access memory you don't own, or by corrupting something you do own, which then misbehaves, causing an illegal memory access, as a side-effect of the bug you created. Apart from the hardware trap, there is no "memory police" except by running debugging tools. – Weather Vane Oct 27 '22 at 12:07

0 Answers0