On 10 Oct 2005 14:06:47 -0700,
wrote:
>I used to think that i knew to program in C but this problem is making
>me thing otherwise.
>i'm trying to do something trivial, i suppose.
>i have this struct:
>
>typedef struct{
>int socket;
>char ip[16];
>}peers;
>
>in a main() i malloc this way:
>Peers=malloc(sizeof(peers));
>Then, my program would eventually want to save more "peers" so
>i said, why dont i Realloc this thing x2 x3 x4 x5 and so on.. as
>needed. So i created this function:
>
>peers* ingresaripsock(peers* lista,int sock, char ip[16],int *tm)
Is *tm a count of how may structures your currently have space for?
>{
>int offset= (*tm)++;
offset is the original value of *tm.
>
>if (offset>0) lista = realloc(lista,offset * sizeof(peers)+1);
What did you think the +1 does. What you have done, if realloc
succeeds, is allocate space for the same number of structures plus one
more byte. You did not allocate space for an extra struct. Did you
really mean
... = realloc(lista, (offset+1) * sizeof(peers));
>
>strcpy((lista + offset)->ip, ip);
As it stands now, this invokes undefined behavior. lista points to an
allocated area capable of holding offset structures. The structures
are numbered 0, 1, ..., offset-1. You are now writing beyond the end
of your allocated area.
>(lista + offset)-> socket=sock;
>
>return lista;
>}
>
>i print the results with:
>
>void imprimirpeers(peers* lista, int tm){
>int i=0;
>
>for(i=0;i<tm;i++){
> printf("Ip: %s - Sock: %d\n",(lista + i) ->ip , (lista + i)
>->socket);
> }
>}
>
>
>but when i printf the Results, it's all weird data. I believe the
>problem is around the Realloc becuase i tried this code but instead of
>using realloc i malloc'd from the first time with space for like 20
>positions (commented the realloc part in the function) and it worked
>just fine. But i want to use what i Really need, dont want to do malloc
>( 20000000) and use a couple of bytes...
>
>
>Please i really need some help-
<<Remove the del for email>>