Problem with memory in C function

Started by Diogo Biazusabout 22 years ago3 messagesgeneral
Jump to latest
#1Diogo Biazus
diogo@ikono.com.br

Hi folks,

Sorry to send this email twice, but I'm having troubles with my email
server.
I'm having troubles writing a function that reads a file from fisk and
return a bytea to database.
Can anyone help me?

I read the entire file into a (char *) and then return it as a bytea:

fseek(file, 0L, SEEK_END);
tamanhoArquivo = ftell(file);
rewind(file);

fileContent = palloc(fileSize + 1);
if(fileContent == NULL )
{
elog(ERROR, "Error alocating memory (%i bytes)", fileSize + 1);
}

fread(fileContent, fileSize, 1, file);
fclose(file);
PG_RETURN_BYTEA_P((bytea *) fileContent);

And, when I call the funcion in psql, it gives me the following message:
ERROR: Memory exhausted in AllocSetAlloc(879718306)

Am I doing something wrong?

TIA,

--
Diogo Biazus
diogo@ikono.com.br
http://www.ikono.com.br

#2Tom Lane
tgl@sss.pgh.pa.us
In reply to: Diogo Biazus (#1)
Re: Problem with memory in C function

Diogo Biazus <diogo@ikono.com.br> writes:

Am I doing something wrong?

You forgot to set up the length word that's required for a bytea value
(or any other variable-length datatype). The system is taking the first
four bytes of the file data as the datum length.

regards, tom lane

#3Diogo Biazus
diogo@ikono.com.br
In reply to: Tom Lane (#2)
Re: Problem with memory in C function

Tom Lane wrote:

Diogo Biazus <diogo@ikono.com.br> writes:

Am I doing something wrong?

You forgot to set up the length word that's required for a bytea value
(or any other variable-length datatype). The system is taking the first
four bytes of the file data as the datum length.

Thanks, now I've got it working.
I've done a bytea_import function, that works like lo_import, but you
put it into a insert statement:

insert into table_name (field_name) values
(bytea_import('/path_to_file_on_server'));

Does anyone think it could be useful in the /contrib?

My Regards,

--
Diogo Biazus
diogo@ikono.com.br
http://www.ikono.com.br