-1

I want to bound *float vec_value (member of struct vec) to be large a defined size. I do with malloc():

     pattern_ptr->vec_value=malloc(dataset.mFeatures * sizeof(float))

To be sure the allocation is done correcty I expect to see a SegFault if VALUE>=dataset.mFeatures when:

     printf("%f\n",pattern_ptr[N].vec_value[VALUE]);

But it compiles and prints the value in the adjacent area in memory.

This is the code:

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

struct vec{
    int id_vec;
    float *vec_value;
};

//prototipi
Dataset loadDataset(void); // struct { int nPattern; int mFeatures; float *dataset_ptr;  }

int main(){

    int i,j;
    Dataset dataset=loadDataset();
    struct vec *pattern_ptr=malloc(dataset.nPattern * sizeof(struct vec));
    pattern_ptr->vec_value=malloc(dataset.mFeatures * sizeof(float));
    for(i=0;i<dataset.nPattern;i++){
        pattern_ptr[i].id_vec=i;
        pattern_ptr[i].vec_value=&dataset.dataset_ptr[i*dataset.mFeatures];
    }

    printf("%f\n",pattern_ptr[1].vec_value[10]);

What's wrong?

Luca Jungla
  • 150
  • 8
  • 2
    Just one [C] question before this one... – Eugene Sh. Jan 09 '19 at 16:37
  • 2
    `To be sure the allocation is done correcty I expect to see a SegFault if VALUE>=dataset.mFeatures` undefined behavior is undefined. – tkausl Jan 09 '19 at 16:37
  • Why it should be undefined? – Luca Jungla Jan 09 '19 at 16:46
  • @LucaJungla This question (in the comment) doesn't make sense. It is undefined if no one have defined it. – Eugene Sh. Jan 09 '19 at 16:48
  • @LucaJungla for speed. C is meant to be close to the hardware and fast. If it had to do bounds checking on every array access, that would add overhead and slow things down (I think java and c# do this, for instance). C happily lets you shoot yourself in the foot if you do something wrong. It's up to the programmer _not_ to do anything wrong. – yano Jan 09 '19 at 16:50
  • Ok now is clear after the answer. – Luca Jungla Jan 09 '19 at 16:51
  • 1
    @LucaJungla We have to do a lot of supposition from your code because it is complicated for nothing and lot of definitions / values are unknown. Please next time just limit your example to the interesting part, could be `int main() { float * p = malloc(2*sizeof(float)); printf("%g\n", p[5]); return 0; }` – bruno Jan 09 '19 at 16:52
  • @bruno Thanks for the advice! – Luca Jungla Jan 09 '19 at 16:53

1 Answers1

0

The C language standard does not mandate bounds checking on array accesses (individual implementations may add bounds checking, but I'm not aware of any that do). Neither does it specify what the behavior should be if you index outside of an array (or malloc'ed buffer). Neither the compiler nor the runtime environment are required to handle the situation in any particular way (the behavior is left undefined).

It's up to the programmer to not read or write past the end of the array.

John Bode
  • 119,563
  • 19
  • 122
  • 198