Help with malloc in c

Hi, when i put numbers differents in n1 and n2, the program stay with error. Help me. Look my code:

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

void contagem(int vet1[], int n1, int vet2[], int n2);

int main()
{
int n1, n2, i;
int *vet1;
int *vet2;

printf("Digite o numero de elementos do vetor 1: ");
scanf("%d", &n1);
while(n1 <= 0 || n1 > 50){
printf("Digite essa budega certa ae!");
printf("Digite o numero de elementos do vetor 1: ");
scanf("%d", &n1);
}

vet1 = (int*) malloc(n1);

printf("Digite o numero de elementos do vetor 2: ");
scanf("%d", &n2);
while(n2 <= 0 || n2 > 50){
printf("Digite essa budega certa ae!");
printf("Digite o numero de elementos do vetor 2: ");
scanf("%d", &n2);
}

vet2 = (int*) malloc(n2);

for(i = 0; i < n1; i++){
printf("Digite o elemento %d do arranjo 1: ", i);
scanf("%d", &vet1[i]);
}

for(i = 0; i < n2; i++){
printf("Digite o elemento %d do arranjo 2: ", i);
scanf("%d", &vet2[i]);
}

contagem(vet1, n1, vet2, n2);

return 0;
}

void contagem(int vet1[], int n1, int vet2[], int n2){
int i;
int j;
for(i = 0; i < n1; i++){
for(j = i + 1; j < n2; j++){
if(vet1[i] == vet2[j]){
printf("%d ", vet1[i]);
}
}
}
}
Please use code tags: [code]Your code[/code]
Read this: http://www.cplusplus.com/articles/z13hAqkS/

You need the provide the exact size in bytes for malloc. You provided just the number of elements. Change

vet1 = (int*) malloc(n1); -> vet1 = (int*) malloc(n1 * sizeof(int));

vet2 = (int*) malloc(n2); -> vet2 = (int*) malloc(n2 * sizeof(int));
Topic archived. No new replies allowed.