0

I ran this C code in CLion and Cygwin toolchain (gcc and gdb) in windows, I tried writing to str[5] which is not allocated:

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

int main() {
    char * str = malloc(4);
    str[5] = 'a';
    printf("%c\n", str[5]);
    return 0;
}

However, it ran without any errors (I was excpecting to get memory access violation and a warning that I didn't free the allocated pointer).

This is how the CMakeLists.txt is configured (I just added the CMAKE_C_FLAGS line):

cmake_minimum_required(VERSION 3.17)
project(myproject C)

set(CMAKE_C_STANDARD 11)

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wextra -Werror")

add_executable(myproject main.c)

Why didn't it throw warning / error for that memory access? How can I fix that?

nscode
  • 147
  • 1
  • 9
  • 1
    Not an exact duplicate since the tag on this is C++, but the answer is the same: https://stackoverflow.com/questions/1239938/accessing-an-array-out-of-bounds-gives-no-error-why – Chase Dec 30 '20 at 14:39
  • You didn't get an access violation message because there was no access violation. Accessing beyond the bounds of an array is _undefined behaviour_ (google that) which may or may not result in an access violation. There are many duplicates of this question. And not freeing a pointer won't give any diagnostic message outside of special debugging environnments. – Jabberwocky Dec 30 '20 at 14:40
  • @Chase When I write the same code in Visual Studio I get an exception thrown. I was expecting the same in CLion. – nscode Dec 31 '20 at 09:48
  • @nscode That is, in fact, what undefined behavior means. It may work, or it may spew dragons out of your nose. – Chase Dec 31 '20 at 09:57
  • 1
    @nscode note that a runtime "exception" is fundamentally different from a compile time warning (which is what you're asking for). The runtime exception has nothing to do with what editor/compiler you use. It depends on what instructions are executed by your program itself and what steps the OS/kernel took to prevent your program from *potentially* damaging the system. – Chase Dec 31 '20 at 09:59
  • @Chase thanks for the explanation, this makes sense. I was probably expecting this run time exception because of my familiarity with Visual Studio. – nscode Dec 31 '20 at 10:36

1 Answers1

0

You are not allowed to access unallocated memory. At the same time your compiler/runtime is not required to prevent you from doing so.

There is no hand holding in C, you are allowed to shoot yourself in the foot if you so desire.

koder
  • 2,038
  • 7
  • 10