compression algorithm

家住魔仙堡 提交于 2019-12-13 09:32:00

问题


I'm working on a compression algorithm wherein we have to write code in C. The program takes a file and removes the most significant bit in every character and stores the compressed text in another file. I wrote a function called compress as shown below. I'm getting a seg fault while freeing out_buf. Any help will be a great pleasure.


回答1:


You close out_fd twice, so of course the second time it is an invalid file descriptor. But more than that, you need to review your use of sizeof() which is NOT the same as finding the buffer size of a dynamically-allocated buffer (sizeof returns the size of the pointer, not the buffer). You don't show the calling code, but using strcat() on a buffer passed-in is always worth a look too (is the buffer passed by the caller large enough for the result?).

Anyway, that should be enough to get you going again...




回答2:


You're closing twice the same file descriptor

  close(out_fd);

  if ( close(out_fd) == -1 )
    oops("Error closing output file", "");

Just remove the first close(out_fd)

The segmentation fault is because you moved the out_buf pointer. If you want to put values inside his malloc'd area, use another temp pointer and move it through this memory area.

Like this:

unsigned char *out_buf = malloc(5400000*7/8);
unsigned char *tmp_buf = out_buf;

then subst every *out_buf++ with *tmp_buf++;

Change also the out_buf inside the write call with tmp_buf



来源:https://stackoverflow.com/questions/15006366/compression-algorithm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!