[해결] 구조체 이중포인터 사용후 메모리 해제

muzie의 이미지

다음과 같은 구조체가 있습니다.

 26 struct network_camera {                                                                
 27     char ip_addr[15]; /* network camera ip address */
 28     char vendor[30]; /* vendor name */                                                 
 29     char product[30]; /* product name */                                               
 30     unsigned int port; /* rtsp bind port number */                                     
 31     unsigned int resolution; /* network camera resolution */                           
 32     unsigned int fps; /* frame rate */                                                 
 33     unsigned int codec_type; /* codec type */                                          
 34     int gop_size;                                                                      
 35 };  

그리고 이 함수를 main에서 포인터로 선언합니다.

netcam *ncam;

이후에 뭔가를 처리하는 함수에 이중포인터로 넘겨주고 그곳에서 메모리를 할당합니다.
axis_init(&ncam);

 8 int
 9 axis_init(netcam **ncam)
 10 {
 11     ncam = (netcam**)malloc(sizeof(struct network_camera*));
 12     ncam[0] = (netcam*)malloc(sizeof(struct network_camera));

메모리 할당후 구조체 값을 변경한 뒤
메모리값을 찍어봤더니 함수를 나오자 이상하게도 변경이 되어있질 않았습니다.
대충 생각해보면 메모리의 참조를 넘겨줬으면 변경이 되어야 할텐데 말이죠.

그리고 다시 main에서 ncam을 free시켜주면 (free(ncam);)
세그멘테이션 폴트가 뜹니다.

제가 뭘 놓치고 있는지를 모르겠네요.
지적해주시면 감사드리겠습니다.

irondog의 이미지

axis_init() 안에서 &ncam과 &ncam[0]의 값 차이가 있는지 찍어 보시길...

제 생각엔

int
axis_init(netcam **ncam)
{
    *ncam = (netcam*)malloc(sizeof(struct network_camera));
이렇게 하면 해결될 문제 같습니다만..

bestyt의 이미지

실제 main()안에 선언된 pointer의 value는 변경되지 않았네요.

netcam *ncam <- 이 변수가 heap에서 할당 받아온 값을 가르킬려고 하였다면,

8 int
9 axis_init(netcam **ncam)
10 {
11 *ncam = (netcam*)malloc(sizeof(struct network_camera));

과 같이 변경하셔야 원래 main에 선언된 pointer의 value값을 변경할수있습니다.

원소스의 오류를 짚어보면,
8 int
9 axis_init(netcam **ncam)
10 {
11 ncam = (netcam**)malloc(sizeof(struct network_camera*)); // 4 byte의 heap을 할당받아 이중포인터값을 채웁니다. Design적으로 input parameter가 변경되는데 이렇게 input parameter가 변경되어도 함수가 return되면 원래 main에서 함수콜할때 넣은 값은 변경이 안됩니다. C의 SWAP예제참고..
12 ncam[0] = (netcam*)malloc(sizeof(struct network_camera)); // 4byte heap을 할당받은 자리에 struct network_camera를 heap할당받은 주소값 저장합니다.
// 즉 ncam <- ncam[0] <- struct network_camera와 같이 포인터가 저장되어 있으나 앞에 말씀드렸다시피, 함수가 return되면 ncam의 변경분은 main쪽으로 반영이 되지않습니다. 즉 할당받은 heap 영역은 memory leak이 발생하고, main쪽에선 여전히 할당되지 않는 값이 있으므로 free를 호출하면 segmentation fault가 발생하는거죠.

muzie의 이미지

답변 감사드립니다.
말씀하셨던대로 시도도 해봤었는데 계속 오류가 떠서..
알고보니 그 전에 사용했던 매크로함수에서 잘못된 메모리 참조가 있어서 죽는거였네요.
신기한건 main이 return 되고서 backtrace도 불가능하고.....

휴..어제 저거때문에 몇시간을 삽질했는지...
이럴때마다 공부 헛한거 아닌가 생각되네요 ㅠㅠ

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.