problem with memory allocation

From: Kjetil Haaland <kjetil(dot)haaland(at)student(dot)uib(dot)no>
To: pgsql-novice(at)postgresql(dot)org
Subject: problem with memory allocation
Date: 2004-11-26 14:56:41
Message-ID: 200411261556.42105.kjetil.haaland@student.uib.no
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

Hello all
Sorry for asking so many question about this topic, but i don't get it to
work. The problem is when i allocate memory for char pointers (char*). I have
a function that i run many times in my db. The first time i allocate memory
for the char* it is ok, and it is set to the length that i say it should
have. In the next round, i give a smaller input and tries to allocate memory
for this.

The first problem is when i try to print out the pointer after the allocation,
but before the insert it is what i inserted the last time i used the
function.
The second problem, coming from the first, is that it has the length from the
first allocation, not the length that i set it to have.
Here is some of the code i use:

alignres *align = (alignres *) PG_GETARG_POINTER(0);
char *first = NULL;
char *second = NULL;
int secondStart=align->secondString;

char tempBuffer[strlen(align->stringBuffer)+1];

elog(NOTICE, "before allocating:first=%s, second=%s", first, second);
first = (char*) palloc(sizeof(char)*secondStart);
second = (char*) palloc(sizeof(char)*(strlen(align->stringBuffer)
-secondStart+1));
elog(NOTICE, "after allocating:first=%s, second=%s", first, second);
elog(NOTICE, "length: first=%d, second=%d", strlen(first), strlen(second));

snprintf(tempBuffer, sizeof(tempBuffer), "%s", align->stringBuffer);
snprintf(first, secondStart, "%s", tempBuffer);
first[strlen(first)] = '\0';

int j=0;
for(i=secondStart-1; i < (strlen(align->stringBuffer)); i++) {
second[j] = tempBuffer[i];
j++;
}
second[strlen(second)] = '\0';

pfree(first);
pfree(second);

I am i doing the allocation correct?
Is there any other way to free the memory so first and second is not set to
the value that the memory was last used for?

thanks
-Kjetil

Responses

Browse pgsql-novice by date

  From Date Subject
Next Message Bruno Wolff III 2004-11-26 15:04:52 Re: Converting file -Invalid data format on input DATE
Previous Message Aarni Ruuhimäki 2004-11-26 13:52:31 Querying a list field against another list