← Back to context Comment by jlarocco 12 years ago Stack allocated objects are cleaned up automatically in C, too... 1 comment jlarocco Reply dllthomas 12 years ago RAII. [1]Stack allocated objects have their memory freed in C. Other resources are not released.Consider the following C, with and without gcc extensions: #include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <fcntl.h> #include <unistd.h> #ifndef GCC_EXTENSIONS #define GCC_EXTENSIONS 1 #endif int main() { { #if GCC_EXTENSIONS void close_fd(int *fdp) { if(*fdp >= 0) close(*fdp); } #else #define __attribute__(...) #endif int fd __attribute__((cleanup(close_fd))) = -1; fd = open("somefile", O_CREAT | O_WRONLY, 0644); system("ls /proc/self/fd"); } system("ls /proc/self/fd"); } with gcc extensions: 0 1 2 3 4 0 1 2 3 without gcc extensions: 0 1 2 3 4 0 1 2 3 4 [1] http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initial...
dllthomas 12 years ago RAII. [1]Stack allocated objects have their memory freed in C. Other resources are not released.Consider the following C, with and without gcc extensions: #include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <fcntl.h> #include <unistd.h> #ifndef GCC_EXTENSIONS #define GCC_EXTENSIONS 1 #endif int main() { { #if GCC_EXTENSIONS void close_fd(int *fdp) { if(*fdp >= 0) close(*fdp); } #else #define __attribute__(...) #endif int fd __attribute__((cleanup(close_fd))) = -1; fd = open("somefile", O_CREAT | O_WRONLY, 0644); system("ls /proc/self/fd"); } system("ls /proc/self/fd"); } with gcc extensions: 0 1 2 3 4 0 1 2 3 without gcc extensions: 0 1 2 3 4 0 1 2 3 4 [1] http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initial...
RAII. [1]
Stack allocated objects have their memory freed in C. Other resources are not released.
Consider the following C, with and without gcc extensions:
with gcc extensions:
without gcc extensions:
[1] http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initial...