Opa, poderia me ajudar?
O caso é o seguinte:
#include <stdlib.h>
#include <stdio.h>
#define tamanho 10
int* alocaVetor(){
int *aux;
aux = (int*) malloc(tamanho * sizeof(int));
}
int multiplica(int *vetorX, int *vetorY){
for(int i = 0; i < tamanho; i++) {
int resto = i % 2;
if(resto == 0){
vetorY[i] = vetorX[i] * 2;
}else{
vetorY[i] = vetorX[i] * 3;
}
}
}
int main() {
int vetorX[tamanho] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int vetorY[tamanho];
multiplica(vetorX, vetorY);
vetorX[tamanho] = alocaVetor(tamanho);
vetorY[tamanho] = alocaVetor(tamanho);
for(int i = 0; i < tamanho; i++){
printf("VetorY eh de: %d\n", vetorY[i]);
}
}
Estou com um problema em que quando eu executo este código com implementação da alocação dinâmica de memória, ele dá esse erro após todo o processo:
“*** stack smashing detected *** : terminated
Aborted”
Output:
VetorY eh de: 6
VetorY eh de: 6
VetorY eh de: 12
VetorY eh de: 10
VetorY eh de: 18
VetorY eh de: 14
VetorY eh de: 24
VetorY eh de: 18
VetorY eh de: 30
*** stack smashing detected ***: terminated
Aborted
Quando eu altero o define para 11, o erro some, mas gera um valor 0 do vetorY, e eu não quero isso. Poderia me ajudar?
#include <stdlib.h>
#include <stdio.h>
#define tamanho 10
int* alocaVetor(){
int *aux;
aux = (int*) malloc(tamanho * sizeof(int));
return aux;
}
int multiplica(int *vetorX, int *vetorY){
for(int i = 0; i < tamanho; i++) {
int resto = i % 2;
if(resto == 0){
vetorY[i] = vetorX[i] * 2;
}else{
vetorY[i] = vetorX[i] * 3;
}
}
}
int main() {
int *vetorX;
int *vetorY;
vetorX = alocaVetor();
vetorY = alocaVetor();
for(int i = 0; i < tamanho; i++){
vetorX[i]=i+1;
}
multiplica(vetorX, vetorY);
for(int i = 0; i < tamanho; i++){
printf("VetorY eh de: %d\n", vetorY[i]);
}
free( vetorX );
free( vetorY );
}
Alterei o código inteiro. Qualquer dúvida entre em contato