I have a script that fills in an array, either by using a function, or not.
It takes in an argument readmode, it decides whether to use the function or not; and an argument len_arr, which decides the length of the array.
I simplified the code so that every iteration the array length increases every iteration, but in actual situation, every iteration i load audio files so that are of different length, hence i use malloc to init, an then i free it once i am done post-processing it.
Main Script
// imports
#include <iostream> /* cout */
#include <stdio.h> /* printf */
#include <stdlib.h> /* atoi */
using namespace std;
void function_1(int len_arr, double * output_buffer){
for (int j=0; j<len_arr; ++j){
output_buffer[j] = 1.0*j;
}
}
int main (int argc, char ** argv) {
int readmode = atoi(argv[1]);
// double *buffer;
// cout << "1 : Memory Address of buffer="<<buffer << endl;
for (int len_arr=1; len_arr<=5; ++len_arr){
if (readmode==1){
double *buffer = (double *)malloc(len_arr * sizeof(double));
function_1(len_arr, (double*)buffer);
cout << "\n2 : Memory Address of buffer="<<buffer << endl;
printf("readmode=1 : buffer[:5]=[%f %f %f %f %f]\n", buffer[0],buffer[1],buffer[2],buffer[3],buffer[4]);
} else if (readmode==2){
double *buffer = (double *)malloc(len_arr * sizeof(double));
for (int j=0; j<len_arr; ++j){
buffer[j] = 1.0*j;
}
cout << "\n3 : Memory Address of buffer="<<buffer << endl;
printf("readmode=2 : buffer[:5]=[%f %f %f %f %f]\n", buffer[0],buffer[1],buffer[2],buffer[3],buffer[4]);
}
/* Do my post-processing with buffer */
// verbose
cout << "\n4 : Memory Address of buffer="<<buffer << endl;
printf("readmode=%i : buffer[:5]=[%f %f %f %f %f]\n", readmode, buffer[0],buffer[1],buffer[2],buffer[3],buffer[4]);
free(buffer);
}
return 0 ;
}
I compiled it like this
g++ -o ./debug_ifelse.out -Ofast -Wall -Wextra -std=c++11 "./debug_ifelse.cpp"
Here are the problems i faced:
- If i dont initialise
double *bufferprior to entering the if-else, i get compilation error that it was not declared, even though i did define it within each of the condition.
./debug_ifelse.cpp: In function ‘int main(int, char**)’:
./debug_ifelse.cpp:41:48: error: ‘buffer’ was not declared in this scope
cout << "\n4 : Memory Address of buffer="<<buffer << endl;
^
./debug_ifelse.cpp: At global scope:
./debug_ifelse.cpp:14:15: warning: unused parameter ‘argc’ [-Wunused-parameter]
int main (int argc, char ** argv) {
^
- When i do initialise it (though i dont see the meaning to), the variable
double *bufferoutside and within the if-else seems to be in different memory address, and i cant access the one that was defined within the if-else.
1 : Memory Address of buffer=0
2 : Memory Address of buffer=0x24f3030
readmode=1 : buffer[:5]=[0.000000 0.000000 0.000000 0.000000 0.000000]
4 : Memory Address of buffer=0
Segmentation fault
Aucun commentaire:
Enregistrer un commentaire