Jump to content
Ragon

Eroare alocare dinamica C

Recommended Posts

Posted

Salut! Am urmatorul program care pentru fiecare valoare citita diferita de -1, aloca in memorie un spatiu si memoriaza in sir elementul. Problema intervine cand introduc al saptelea element, programul imi da eroare si nu inteleg de ce.

Eroarea: realloc(): invalid next size: 0x0000000001bf7010

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


void citire(int*p) {
int e,t=1;
printf("E 1:");scanf("%d",&e);
while(e!=-1) {
p=(int*)realloc(p,t*sizeof(int));//Acloca spatiu
if(p==0) {printf("Nu s-a alocat memorie!"); exit(1);}
*(p+t)=e;//adauga elem citit la sir
t++;//inc dim sirului
printf("%p %d",p,t);
printf("E %d:",t);scanf("%d",&e);
}
*p=t-1;//retine dim sirului in p[0]
}

void afisare(int*p) {
int i;
for(i=1;i<=*p;i++) printf("%d ",*(p+i));
printf("\n");
}

int main()
{
int*x=malloc(0);
citire(x);
return 0;
}

Posted
*(p+t-1)=e; //adauga elem citit la sir

te duci cu o adresa mai departe decat trebuie.

Asta era problema. Mersi!

Oare de ce programul merge pana la al 7-lea element? De ce nu da eroarea de la primu? Cand am alocata pozitia 0 si incerc sa memorez pe 1.

Algoritmul functional(in *p este lungimea sirului):

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


void citire(int*p) {
int e,t=1;
printf("E 1:");scanf("%d",&e);
while(e!=-1) {
p=(int*)realloc(p,(t+1)*sizeof(int));
if(p==0) {printf("Nu s-a alocat memorie!"); exit(1);}
*(p+t)=e;
t++;
printf("%p %d",p,t);
printf("E %d:",t);scanf("%d",&e);
}
*p=t-1;
}

void afisare(int*p) {
int i;
for(i=1;i<=*p;i++) printf("%d ",*(p+i));
printf("\n");
}

int main()
{
int*x=malloc(0);
citire(x);
afisare(x);
return 0;
}

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...