本文介绍了io.Copy在golang中导致内存不足的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用io.Copy()复制一个大约700Mb的文件,但它会导致内存不足

  bodyBuf: =&; bytes.Buffer {} 
bodyWriter:= multipart.NewWriter(bodyBuf)

//关键步骤
fileWriter,err:= bodyWriter.CreateFormFile(paramName,fileName)
if err!= nil {
return nil,err
}

file,err:= os.Open(fileName)//文件大小约为700Mb
if err!= nil {
return nil,err
}
推迟file.Close()

// iocopy
copyLen, err:= io.Copy(fileWriter,file)//这会导致内存不足
if err!= nil {
fmt.Println(io.copy():,err)

return nil,err
}

错误信息如下:

 运行时:由OS分配的内存(0x752cf000)不在可用范围内[0x18700000,0x98700000)
运行时:内存不足:无法分配1080229888字节块(1081212928使用中)
致命错误:内存不足
 buf := make([] byte,766509056) bodyBuf:= bytes.NewBuffer(buf) bodyWriter:= multipart.NewWriter(bodyBuf) $ b $ fileWriter,err:= bodyWriter .CreateFormFile(paramName,fileName)//内存不足 if err!= nil { return nil,err }  
解决方案
 bodyBuf 


 multipart  bytes.Buffer  multipart.NewWriter 

I use io.Copy() to copy a file, about 700Mb, but it cause out of memory

bodyBuf := &bytes.Buffer{}
bodyWriter := multipart.NewWriter(bodyBuf)

//key step
fileWriter, err := bodyWriter.CreateFormFile(paramName, fileName)
if err != nil {
    return nil, err
}

file, err := os.Open(fileName) //the file size is about 700Mb
if err != nil {
    return nil, err
}
defer file.Close()

//iocopy
copyLen, err := io.Copy(fileWriter, file) // this cause out of memory
if err != nil {
    fmt.Println("io.copy(): ", err)

    return nil, err
}

The error message as follow:

runtime: memory allocated by OS (0x752cf000) not in usable range [0x18700000,0x98700000)
runtime: out of memory: cannot allocate 1080229888-byte block (1081212928 in use)
fatal error: out of memory

I allocate enough memory for buf, it cause out of memory in bodyWriter.CreateFormFile()

buf := make([]byte, 766509056)
bodyBuf := bytes.NewBuffer(buf)
bodyWriter := multipart.NewWriter(bodyBuf)

fileWriter, err := bodyWriter.CreateFormFile(paramName, fileName) // out of memory
if err != nil {
    return nil, err
}
解决方案
bodyBuf
multipartbytes.Buffermultipart.NewWriter

这篇关于io.Copy在golang中导致内存不足的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!