-1

I seem to have a problem with reallocating memory of arrays inside a function. Whenever the code gets to realloc, it is shut down due to Segmentation fault.

I call malloc in main:

char* coded_message = (char*) malloc(BASE_LENGTH * sizeof(char));
read_input(&coded_message, &original_message, &char_counter);

Than pass it to a function, which is reading input an if needed be reallocates the memory. So I the function goes like this:

int read_input(char** coded_message){
    ...
    *coded_message = (char*) realloc(*coded_message, (counter + REALLOC_LENGTH) * sizeof(char));
    ...
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
iandorr
  • 1
  • 4
  • you just edited the code to be substantially different, please do not do that. If you have a new question then post a new question, and include a [MCVE](https://stackoverflow.com/help/mcve) – M.M Nov 30 '18 at 07:46
  • That answer does not help me at all – iandorr Nov 30 '18 at 08:01
  • The duplicate answered the code you originally posted. Now you edit the question to be completely different. – M.M Nov 30 '18 at 08:23

1 Answers1

1

C uses pass-by value. The function arguments are passed by value to the called function, thus any chnages made to the argument will not reflect back to the caller.

In this case, from the function read_input(), the assignment (return value of realloc()) to the original_message will not reflect back to the caller, main().

In other words, you can change the content pointed to by read_input, can be changed, but the read_input itself cannot be changed. If you want to change the pointer itself, you need to pass a pointer to the pointer.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • You need to use char** blah, and modify/use *blah – Skriptkiddie Nov 30 '18 at 07:12
  • sorry - don't really know how to format comments properly.So I the function uses `int read_input(char** coded_message){*coded_message = (char*) realloc(*coded_message, (counter + REALLOC_LENGTH) * sizeof(char));}`while in the main I first call malloc like this `char* coded_message = (char*) malloc(BASE_LENGTH * sizeof(char));` So are you saying in the main it should be a pointer to a pointer ** and I should use pointer * in function arguments? – iandorr Nov 30 '18 at 07:23
  • You need to pass a pointer to `read_input` itself, like `&read_input`. – Sourav Ghosh Nov 30 '18 at 07:46