Invalid memory address or nil pointer dereference : help req

Hi Everyone. I am falling into this error for sometime now and I am not able to fix it. I am trying to insert data into db after iterating thru an object with a simple insert statement. But when it hits the part where you insert the data into the database, it throws this error

//Error starts
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0xd2c89f]

and other lines

//Error ends

The code snippet that i am using to insert the data into the db is as follows,

//code begins
for _, data := range Reportdata {
fmt.Println(“enter the loop…”)
err := repo.Db.QueryRow(“insert into savings_data (orgId,cid,bill_name,resource_id,usage_day,resource_type,total_hrs,total_ondem_hrs,total_ri_hrs,ondemand_rate,tot_res_cost,actual_ondem_cost,pot_ondem_hrs,pot_ondem_cost,saving,actual_saving,fee) values($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17) RETURNING id;”, orgID, data.ID, data.Name, data.ResourceID, data.Day, data.Type, data.TotalHrs, data.TotalOnDemandhrs, data.TotalRIHrs, data.OndemandRate, data.TotalResCost,
data.ActualOnDemandCost, data.PotentialOnDemandHrs, data.PotentialOnDemandCost, data.Saving, data.ActualSaving, data.Fee).Scan(&id)

	counter = counter + 1

//code ends

Here the Reportdata is an array of a struct that we have created and I am iterating thru the values that are found in it and inserting it into a db. I have tried several ways but I am not able to fix it. Any help on this will be greately appreciated.

check if you have the proper db connection because usually the nil pointer deference is always due to the sql library using the db variable to access the connection from the connection pool.

Those are usually the important ones, as they do not only tell what happened, but they tell you where it happened.

To be able to successfully debug crashes, you need to know what and where the problem happened.

Also a lot more of context might be currently missing…

1 Like

Hi Vivekab,

i have checked the postgres connection. The connection health while running the application seems to be fine because or else it would prompt me with error on the db connection part, I am fairly surprised that the object is holding the values and the column names of the table that i am referring to add the values are also equally correct but still the code ends up with a null pointer exception even thought it shouldn’t be. Thanks for your tip. If you feel that something else might be the issue, please feel free to mention it. i will check on those grounds as well.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.