I may have an error in my code but just by commenting an int asignment that is not even executed is the difference between a segmentation fault and a successfull run of the program. Why does this happen?
C code:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
//keep it > 0
#define DEFAULT_SIZE 50
struct List* init_list();
struct InternalString{
struct List* l;
};
struct List{
struct List * prev;
int max_pos;
int curr_pos;
char value[];
};
typedef struct{
int len;
struct InternalString* __internal__;
} String;
// string constructor
String build(){
String str;
// creates List with an array of max length = DEFAULT_SIZE
struct List* l = init_list(DEFAULT_SIZE);
struct InternalString inter;
inter.l = l;
str.__internal__ = &inter;
str.len = 0;
return str;
}
struct List* init_list(int length){
struct List* l = malloc((length * sizeof(char))+sizeof(struct List));
l->curr_pos = -1;
l->max_pos = length-1;
l->prev = NULL;
return l;
}
void push(char* str, String src){
struct List* l = src.__internal__->l;
int space = l->max_pos - l->curr_pos;
int i = 0;
for (; i < l->max_pos; i++){
if (str[i] == '\0'){
printf("RETURNED\n"); // <---------- Run with the problematic line commented to see that it returns here.
return;
}
l->value[++(l->curr_pos)] = str[i];
}
int needed_space;
//int i_clone = i; // <---------- uncommenting this line provoques the segmentation fault
}
// tests
int main(){
String st = build();
push("defg", st);
}
I'm compiling with gcc 9.4.0 on ubuntu