samedi 28 février 2015

Address is 0 bytes after a block of size 1,024 alloc'd



I ran valgrind on my program and it told me there an address is of size 0 after alloc-ing 1024 bytes. The code:



unsigned char *dir_buf = malloc(1024 * sizeof(unsigned char));
assert(dir_buf);


The log:



==30231== Address 0x51fd540 is 0 bytes after a block of size 1,024 alloc'd
==30231== at 0x4C2ABA0: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==30231== by 0x40153C: do_pass1 (pass1.c:25)
==30231== by 0x4019EC: do_pass1 (pass1.c:144)
==30231== by 0x401B0F: pass1 (pass1.c:184)
==30231== by 0x4010E8:
main (blah.c:225)


Any idea why? I'm getting an invalid read size of 4 when I use that pointer.



dir = (struct ext2_dir_entry_2 *)(dir_buf);
if(dir->inode == 0) break; //INVALID READ



How to create a Evony like map



I am currently working on a game very similar to Evony. I already know how to do pretty much everything except create the map for the game and the cords, if this make sense. Can aomeone guide me here?


I want ro make the game either in Html5 and javadcript or C


Thanks




How to write or read memory without touching cache



Is there any way to write/read memory without touching L1/L2/L3 cache under x86 CPUs?


And is cache in x86 CPUs totally managed by hardware?



EDIT: I want to do this because I want to sample the speed of memory and see if any part of memory's performance degrades.





Only first and last GTK3 Combo Box Entry Working



I use C switch based on a variable I set according to which GTK Combo Box Text entry is selected ( variable = 3 <===> case 3: ... etc. ). There are 4 entries. My trouble is getting the 2nd and 3rd entries to actually do something.


Only the first and last entries seem to carry the variable value properly.


I have tested it repeatedly, seeing if I need to use if/else rather than a switch, to no avail. It is probably more than a coincidence, though, that the middle two entries are ignored in the program. Right now, I am using 4 if/else statements. There is the same behaviour, however, with switch (only the first and last entries cause the program to do something, which, in my case, is cause a dialog box to show and then, upon clicking, launch a terminal window showing progress).


Please, please, help is much appreciated.


Thanks.


P.S. I am using GTK3.




SDL2 Mac OS X Strange memory leaks



I'm writing a little wrapper to learn a bit about C and SDL2 in the same way.


Today i've decided to launch valgrind to test it and see it in action.


Well, the results are pretty scary! It seems to be like some others dyn libs on my system are leaking as hell! (We can clearly see SDL2 and OpenGL but the GPU driver seems in bad state too) : (running on mac os x yosemite). I've also pasted my code and i didn't see something wrong since i'm not allocating memory on the heap by hand. SDL2 is doing it on his own.



==35991== Memcheck, a memory error detector
==35991== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==35991== Using Valgrind-3.11.0.SVN and LibVEX; rerun with -h for copyright info
==35991== Command: ./QSDL
==35991==
--35991-- ./QSDL:
--35991-- dSYM directory is missing; consider using --dsymutil=yes
==35991== Thread 2:
==35991== Invalid read of size 32
==35991== at 0x102908C1D: _platform_memchr$VARIANT$Haswell (in /usr/lib/system/libsystem_platform.dylib)
==35991== by 0x10291C93A: pthread_setname_np (in /usr/lib/system/libsystem_pthread.dylib)
==35991== by 0x10004272A: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x100042C64: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x100042708: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x10291C2FB: _pthread_body (in /usr/lib/system/libsystem_pthread.dylib)
==35991== by 0x10291C278: _pthread_start (in /usr/lib/system/libsystem_pthread.dylib)
==35991== by 0x10291A4B0: thread_start (in /usr/lib/system/libsystem_pthread.dylib)
==35991== Address 0x109b53a80 is 32 bytes before a block of size 16 in arena "client"
==35991==
==35991== Invalid read of size 32
==35991== at 0x102908C1D: _platform_memchr$VARIANT$Haswell (in /usr/lib/system/libsystem_platform.dylib)
==35991== by 0x10291C980: pthread_setname_np (in /usr/lib/system/libsystem_pthread.dylib)
==35991== by 0x10004272A: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x100042C64: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x100042708: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x10291C2FB: _pthread_body (in /usr/lib/system/libsystem_pthread.dylib)
==35991== by 0x10291C278: _pthread_start (in /usr/lib/system/libsystem_pthread.dylib)
==35991== by 0x10291A4B0: thread_start (in /usr/lib/system/libsystem_pthread.dylib)
==35991== Address 0x109b53a80 is 32 bytes before a block of size 16 in arena "client"
==35991==
--35991-- UNKNOWN __pthread_sigmask is unsupported.
--35991-- UNKNOWN host message [id 412, to mach_host_self(), reply 0x1003]
--35991-- UNKNOWN host message [id 222, to mach_host_self(), reply 0x1003]
--35991-- UNKNOWN mach_msg unhandled MACH_SEND_TRAILER option
--35991-- UNKNOWN __pthread_sigmask is unsupported. (repeated 2 times)
--35991-- UNKNOWN mach_msg unhandled MACH_SEND_TRAILER option (repeated 2 times)
--35991-- UNKNOWN host message [id 222, to mach_host_self(), reply 0x1803]
--35991-- UNKNOWN mach_msg unhandled MACH_SEND_TRAILER option (repeated 4 times)
--35991-- UNKNOWN mach_msg unhandled MACH_SEND_TRAILER option (repeated 8 times)
--35991-- UNKNOWN host message [id 222, to mach_host_self(), reply 0x30f]
==35991== Thread 1:
==35991== Conditional jump or move depends on uninitialised value(s)
==35991== at 0x105207C1D: _LSApplicationCheckIn (in /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/LaunchServices)
==35991== by 0x107E08565: _RegisterApplication (in /System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/HIServices.framework/Versions/A/HIServices)
==35991== by 0x107E06C88: GetCurrentProcess (in /System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/HIServices.framework/Versions/A/HIServices)
==35991== by 0x100043D99: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x100047A12: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x100079911: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x10004025A: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x100000972: initScreen (in ./QSDL)
==35991== by 0x100000D04: main (in ./QSDL)
==35991==
--35991-- UNKNOWN host message [id 222, to mach_host_self(), reply 0x30f] (repeated 2 times)
--35991-- UNKNOWN host message [id 222, to mach_host_self(), reply 0x1803] (repeated 2 times)
--35991-- UNKNOWN mach_msg unhandled MACH_SEND_TRAILER option (repeated 16 times)
--35991-- UNKNOWN host message [id 222, to mach_host_self(), reply 0x30f] (repeated 4 times)
--35991-- UNKNOWN host message [id 222, to mach_host_self(), reply 0x1803] (repeated 4 times)
--35991-- UNKNOWN mach_msg unhandled MACH_SEND_TRAILER option (repeated 32 times)
--35991-- UNKNOWN host message [id 222, to mach_host_self(), reply 0x1803] (repeated 8 times)
--35991-- UNKNOWN mach_msg unhandled MACH_SEND_TRAILER option (repeated 64 times)
--35991-- UNKNOWN host message [id 222, to mach_host_self(), reply 0x30f] (repeated 8 times)
--35991-- UNKNOWN host message [id 222, to mach_host_self(), reply 0x3c0b]
--35991-- UNKNOWN host message [id 222, to mach_host_self(), reply 0x3c0b] (repeated 2 times)
--35991-- UNKNOWN host message [id 222, to mach_host_self(), reply 0x2e0b]
--35991-- UNKNOWN host message [id 222, to mach_host_self(), reply 0x2e0b] (repeated 2 times)
--35991-- UNKNOWN host message [id 222, to mach_host_self(), reply 0x2e0b] (repeated 4 times)
--35991-- UNKNOWN host message [id 222, to mach_host_self(), reply 0x30f] (repeated 16 times)
--35991-- UNKNOWN host message [id 222, to mach_host_self(), reply 0x3c0b] (repeated 4 times)
--35991-- UNKNOWN mach_msg unhandled MACH_SEND_TRAILER option (repeated 128 times)
--35991-- UNKNOWN host message [id 222, to mach_host_self(), reply 0x3c0b] (repeated 8 times)
--35991-- UNKNOWN host message [id 222, to mach_host_self(), reply 0x2e0b] (repeated 8 times)
--35991-- UNKNOWN task message [id 4816, to mach_task_self(), reply 0x30f]
--35991-- UNKNOWN mach_msg unhandled MACH_SEND_TRAILER option (repeated 256 times)
--35991-- UNKNOWN host message [id 222, to mach_host_self(), reply 0x6217]
--35991-- UNKNOWN host message [id 222, to mach_host_self(), reply 0x6217] (repeated 2 times)
--35991-- UNKNOWN task message [id 4816, to mach_task_self(), reply 0x6217]
--35991-- UNKNOWN host message [id 222, to mach_host_self(), reply 0x621b]
--35991-- UNKNOWN host message [id 222, to mach_host_self(), reply 0x621b] (repeated 2 times)
==35991== Invalid write of size 8
==35991== at 0x123400003F8B: IntelStateHeaps::allocateHeap(IntelStateHeaps::HeapInfo&, unsigned int, unsigned int) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x123400003EA3: IntelStateHeaps::initHeaps(GLDShareGroupRec*) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x123400003919: GenContext::Initialize(GLDContextRec*) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x123400002FF9: Gen7Context::Initialize(GLDContextRec*) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x1234000029E7: glrInitializeContext (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x10EF7FE96: gldCreateContext (in /System/Library/PrivateFrameworks/GPUSupport.framework/Versions/A/Libraries/libGPUSupportMercury.dylib)
==35991== by 0x11113581E: gliCreateContextWithShared (in /System/Library/Frameworks/OpenGL.framework/Versions/A/Resources/GLEngine.bundle/GLEngine)
==35991== by 0x100533B32: CGLCreateContext (in /System/Library/Frameworks/OpenGL.framework/Versions/A/OpenGL)
==35991== by 0x1014C1E1B: -[NSOpenGLContext initWithFormat:shareContext:] (in /System/Library/Frameworks/AppKit.framework/Versions/C/AppKit)
==35991== by 0x100046928: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x100046F77: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x10007EA23: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== Address 0x11314a038 is not stack'd, malloc'd or (recently) free'd
==35991==
==35991== Invalid write of size 8
==35991== at 0x123400003F93: IntelStateHeaps::allocateHeap(IntelStateHeaps::HeapInfo&, unsigned int, unsigned int) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x123400003EA3: IntelStateHeaps::initHeaps(GLDShareGroupRec*) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x123400003919: GenContext::Initialize(GLDContextRec*) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x123400002FF9: Gen7Context::Initialize(GLDContextRec*) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x1234000029E7: glrInitializeContext (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x10EF7FE96: gldCreateContext (in /System/Library/PrivateFrameworks/GPUSupport.framework/Versions/A/Libraries/libGPUSupportMercury.dylib)
==35991== by 0x11113581E: gliCreateContextWithShared (in /System/Library/Frameworks/OpenGL.framework/Versions/A/Resources/GLEngine.bundle/GLEngine)
==35991== by 0x100533B32: CGLCreateContext (in /System/Library/Frameworks/OpenGL.framework/Versions/A/OpenGL)
==35991== by 0x1014C1E1B: -[NSOpenGLContext initWithFormat:shareContext:] (in /System/Library/Frameworks/AppKit.framework/Versions/C/AppKit)
==35991== by 0x100046928: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x100046F77: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x10007EA23: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== Address 0x11314a030 is not stack'd, malloc'd or (recently) free'd
==35991==
==35991== Invalid write of size 8
==35991== at 0x123400003F9B: IntelStateHeaps::allocateHeap(IntelStateHeaps::HeapInfo&, unsigned int, unsigned int) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x123400003EA3: IntelStateHeaps::initHeaps(GLDShareGroupRec*) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x123400003919: GenContext::Initialize(GLDContextRec*) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x123400002FF9: Gen7Context::Initialize(GLDContextRec*) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x1234000029E7: glrInitializeContext (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x10EF7FE96: gldCreateContext (in /System/Library/PrivateFrameworks/GPUSupport.framework/Versions/A/Libraries/libGPUSupportMercury.dylib)
==35991== by 0x11113581E: gliCreateContextWithShared (in /System/Library/Frameworks/OpenGL.framework/Versions/A/Resources/GLEngine.bundle/GLEngine)
==35991== by 0x100533B32: CGLCreateContext (in /System/Library/Frameworks/OpenGL.framework/Versions/A/OpenGL)
==35991== by 0x1014C1E1B: -[NSOpenGLContext initWithFormat:shareContext:] (in /System/Library/Frameworks/AppKit.framework/Versions/C/AppKit)
==35991== by 0x100046928: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x100046F77: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x10007EA23: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== Address 0x11314a028 is not stack'd, malloc'd or (recently) free'd
==35991==
==35991== Invalid write of size 8
==35991== at 0x123400003FA3: IntelStateHeaps::allocateHeap(IntelStateHeaps::HeapInfo&, unsigned int, unsigned int) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x123400003EA3: IntelStateHeaps::initHeaps(GLDShareGroupRec*) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x123400003919: GenContext::Initialize(GLDContextRec*) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x123400002FF9: Gen7Context::Initialize(GLDContextRec*) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x1234000029E7: glrInitializeContext (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x10EF7FE96: gldCreateContext (in /System/Library/PrivateFrameworks/GPUSupport.framework/Versions/A/Libraries/libGPUSupportMercury.dylib)
==35991== by 0x11113581E: gliCreateContextWithShared (in /System/Library/Frameworks/OpenGL.framework/Versions/A/Resources/GLEngine.bundle/GLEngine)
==35991== by 0x100533B32: CGLCreateContext (in /System/Library/Frameworks/OpenGL.framework/Versions/A/OpenGL)
==35991== by 0x1014C1E1B: -[NSOpenGLContext initWithFormat:shareContext:] (in /System/Library/Frameworks/AppKit.framework/Versions/C/AppKit)
==35991== by 0x100046928: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x100046F77: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x10007EA23: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== Address 0x11314a020 is not stack'd, malloc'd or (recently) free'd
==35991==
==35991== Invalid write of size 8
==35991== at 0x123400003FAB: IntelStateHeaps::allocateHeap(IntelStateHeaps::HeapInfo&, unsigned int, unsigned int) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x123400003EA3: IntelStateHeaps::initHeaps(GLDShareGroupRec*) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x123400003919: GenContext::Initialize(GLDContextRec*) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x123400002FF9: Gen7Context::Initialize(GLDContextRec*) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x1234000029E7: glrInitializeContext (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x10EF7FE96: gldCreateContext (in /System/Library/PrivateFrameworks/GPUSupport.framework/Versions/A/Libraries/libGPUSupportMercury.dylib)
==35991== by 0x11113581E: gliCreateContextWithShared (in /System/Library/Frameworks/OpenGL.framework/Versions/A/Resources/GLEngine.bundle/GLEngine)
==35991== by 0x100533B32: CGLCreateContext (in /System/Library/Frameworks/OpenGL.framework/Versions/A/OpenGL)
==35991== by 0x1014C1E1B: -[NSOpenGLContext initWithFormat:shareContext:] (in /System/Library/Frameworks/AppKit.framework/Versions/C/AppKit)
==35991== by 0x100046928: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x100046F77: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x10007EA23: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== Address 0x11314a018 is not stack'd, malloc'd or (recently) free'd
==35991==
==35991== Invalid write of size 8
==35991== at 0x123400003FB3: IntelStateHeaps::allocateHeap(IntelStateHeaps::HeapInfo&, unsigned int, unsigned int) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x123400003EA3: IntelStateHeaps::initHeaps(GLDShareGroupRec*) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x123400003919: GenContext::Initialize(GLDContextRec*) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x123400002FF9: Gen7Context::Initialize(GLDContextRec*) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x1234000029E7: glrInitializeContext (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x10EF7FE96: gldCreateContext (in /System/Library/PrivateFrameworks/GPUSupport.framework/Versions/A/Libraries/libGPUSupportMercury.dylib)
==35991== by 0x11113581E: gliCreateContextWithShared (in /System/Library/Frameworks/OpenGL.framework/Versions/A/Resources/GLEngine.bundle/GLEngine)
==35991== by 0x100533B32: CGLCreateContext (in /System/Library/Frameworks/OpenGL.framework/Versions/A/OpenGL)
==35991== by 0x1014C1E1B: -[NSOpenGLContext initWithFormat:shareContext:] (in /System/Library/Frameworks/AppKit.framework/Versions/C/AppKit)
==35991== by 0x100046928: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x100046F77: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x10007EA23: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== Address 0x11314a010 is not stack'd, malloc'd or (recently) free'd
==35991==
==35991== Invalid write of size 8
==35991== at 0x123400003FBB: IntelStateHeaps::allocateHeap(IntelStateHeaps::HeapInfo&, unsigned int, unsigned int) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x123400003EA3: IntelStateHeaps::initHeaps(GLDShareGroupRec*) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x123400003919: GenContext::Initialize(GLDContextRec*) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x123400002FF9: Gen7Context::Initialize(GLDContextRec*) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x1234000029E7: glrInitializeContext (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x10EF7FE96: gldCreateContext (in /System/Library/PrivateFrameworks/GPUSupport.framework/Versions/A/Libraries/libGPUSupportMercury.dylib)
==35991== by 0x11113581E: gliCreateContextWithShared (in /System/Library/Frameworks/OpenGL.framework/Versions/A/Resources/GLEngine.bundle/GLEngine)
==35991== by 0x100533B32: CGLCreateContext (in /System/Library/Frameworks/OpenGL.framework/Versions/A/OpenGL)
==35991== by 0x1014C1E1B: -[NSOpenGLContext initWithFormat:shareContext:] (in /System/Library/Frameworks/AppKit.framework/Versions/C/AppKit)
==35991== by 0x100046928: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x100046F77: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x10007EA23: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== Address 0x11314a008 is not stack'd, malloc'd or (recently) free'd
==35991==
==35991== Invalid write of size 8
==35991== at 0x123400003FC3: IntelStateHeaps::allocateHeap(IntelStateHeaps::HeapInfo&, unsigned int, unsigned int) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x123400003EA3: IntelStateHeaps::initHeaps(GLDShareGroupRec*) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x123400003919: GenContext::Initialize(GLDContextRec*) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x123400002FF9: Gen7Context::Initialize(GLDContextRec*) (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x1234000029E7: glrInitializeContext (in /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver)
==35991== by 0x10EF7FE96: gldCreateContext (in /System/Library/PrivateFrameworks/GPUSupport.framework/Versions/A/Libraries/libGPUSupportMercury.dylib)
==35991== by 0x11113581E: gliCreateContextWithShared (in /System/Library/Frameworks/OpenGL.framework/Versions/A/Resources/GLEngine.bundle/GLEngine)
==35991== by 0x100533B32: CGLCreateContext (in /System/Library/Frameworks/OpenGL.framework/Versions/A/OpenGL)
==35991== by 0x1014C1E1B: -[NSOpenGLContext initWithFormat:shareContext:] (in /System/Library/Frameworks/AppKit.framework/Versions/C/AppKit)
==35991== by 0x100046928: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x100046F77: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x10007EA23: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== Address 0x11314a000 is not stack'd, malloc'd or (recently) free'd
==35991==
--35991-- UNKNOWN host message [id 222, to mach_host_self(), reply 0x1803] (repeated 16 times)
==35991== Conditional jump or move depends on uninitialised value(s)
==35991== at 0x1112162CF: glViewportArrayv_Core (in /System/Library/Frameworks/OpenGL.framework/Versions/A/Resources/GLEngine.bundle/GLEngine)
==35991== by 0x11114AEAD: glViewport_Exec (in /System/Library/Frameworks/OpenGL.framework/Versions/A/Resources/GLEngine.bundle/GLEngine)
==35991== by 0x10009A255: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x10009BE95: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x1000982B2: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x10007F293: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x100000A2A: initScreen (in ./QSDL)
==35991== by 0x100000D04: main (in ./QSDL)
==35991==
==35991== Conditional jump or move depends on uninitialised value(s)
==35991== at 0x1112162CF: glViewportArrayv_Core (in /System/Library/Frameworks/OpenGL.framework/Versions/A/Resources/GLEngine.bundle/GLEngine)
==35991== by 0x11114AEAD: glViewport_Exec (in /System/Library/Frameworks/OpenGL.framework/Versions/A/Resources/GLEngine.bundle/GLEngine)
==35991== by 0x10009A255: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x10007F356: ??? (in /Library/Frameworks/SDL2.framework/Versions/A/SDL2)
==35991== by 0x100000A2A: initScreen (in ./QSDL)
==35991== by 0x100000D04: main (in ./QSDL)
==35991==
--35991-- UNKNOWN host message [id 222, to mach_host_self(), reply 0x621b] (repeated 4 times)
==35991==
==35991== HEAP SUMMARY:
==35991== in use at exit: 4,963,922 bytes in 13,493 blocks
==35991== total heap usage: 86,557 allocs, 73,064 frees, 180,996,329 bytes allocated
==35991==
==35991== LEAK SUMMARY:
==35991== definitely lost: 123,533 bytes in 363 blocks
==35991== indirectly lost: 575,572 bytes in 3,074 blocks
==35991== possibly lost: 1,619,730 bytes in 2,120 blocks
==35991== still reachable: 2,645,087 bytes in 7,936 blocks
==35991== suppressed: 0 bytes in 0 blocks
==35991== Rerun with --leak-check=full to see details of leaked memory
==35991==
==35991== For counts of detected and suppressed errors, rerun with: -v
==35991== Use --track-origins=yes to see where uninitialised values come from
==35991== ERROR SUMMARY: 29 errors from 13 contexts (suppressed: 131 from 23)


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <SDL2/SDL.h>


//Globals
SDL_Window* window = NULL;
SDL_Renderer* renderer = NULL;

int initScreen(unsigned int w, unsigned int h, const char * title) {

if (w < 1 || h < 1) {
printf("ERROR: width / height are invalid\n");
return -1;
}

//SDL_INIT_EVERYTHING flag to init all SDL components
if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
printf("ERROR: Unable to init SDL: %s\n", SDL_GetError());
SDL_Quit();
return -1;
}

//Init window
window = SDL_CreateWindow(title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, w, h, SDL_WINDOW_SHOWN);
if (window == NULL) {
printf("ERROR: Unable to create window: %s\n", SDL_GetError());
SDL_DestroyWindow(window);
SDL_Quit();
return -1;
}

//Init renderer to take advantage of GPU
renderer = SDL_CreateRenderer(window, -1, 0);
if (renderer == NULL) {
printf("ERROR: Unable to create renderer: %s\n", SDL_GetError());
SDL_DestroyRenderer(renderer);
SDL_Quit();
return -1;
}

return 0;
}


SDL_Texture* loadTexture(const char * fpath) {

SDL_Texture* texture = NULL;
SDL_Surface* surface = NULL;

if (strlen(fpath) == 0) {
printf("ERROR: No path given\n");
}
else {
surface = SDL_LoadBMP(fpath);
if (surface == NULL) {
printf("ERROR: %s\n", SDL_GetError());
}
else {
texture = SDL_CreateTextureFromSurface(renderer, surface);
if (texture == NULL) {
printf("ERROR: %s\n", SDL_GetError());
SDL_DestroyTexture(texture);
}
SDL_FreeSurface(surface);
}
}

return texture;
}

void drawTexture(SDL_Texture * texture) {

if (texture == NULL) {
printf("ERROR: Can't draw an undefined texture\n");
}

SDL_RenderCopy(renderer, texture, NULL, NULL);
}

void clear() {
SDL_RenderClear(renderer);
}

void update() {
SDL_RenderPresent(renderer);
}

//Texture processing helper
void genXOR(unsigned int w, unsigned int h) {

for(unsigned int x = 0; x < w; x++) {
for(unsigned int y = 0; y < h; y++) {
Uint8 c = x ^ y;
SDL_SetRenderDrawColor(renderer, c, c, c, 255);
SDL_Rect rect = {x, y, w, h};
SDL_RenderFillRect(renderer, &rect);
}
}

}

int main() {
initScreen(640, 480, "Main");

// clear();
// genXOR(640, 480);
// update();

SDL_Delay(3000);

renderer = NULL;
window = NULL;
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_QuitSubSystem(SDL_INIT_EVERYTHING);
SDL_Quit();
return EXIT_SUCCESS;
}


My question is : Have you ever experienced something like that ? and what can i do now about these leaks since all my "own" code is about automatic allocation on the stack.




OpenGL - Undefined references to GLUT [duplicate]




I'm having a problem getting openGL to work on Windows 7 using MinGW at the moment. I'm following the steps found here: http://ift.tt/1EWAuOZ


I have installed MinGW and all of it's basic installation files. I have added the elements required to my PATH variable. I have downloaded and placed the GLUT files in the correct directories as described in the link above. Even so, with the below code I get the subsequent errors.



#include <GL/glut.h>

void display (void)
{
glClear (GL_COLOR_BUFFER_BIT);

glBegin (GL_POLYGON);
glVertex2f (-0.5, -0.5);
glVertex2f (-0.5, 0.5);
glVertex2f (0.5, 0.5);
glVertex2f (0.5, -0.5);
glEnd ();

glFlush ();
return;
}

int main (int argc, char **argv)
{
glutInit (&argc, argv);
glutCreateWindow ("simple");
glutDisplayFunc (display);
glutMainLoop ();
}


The command used to compile this program is: gcc firstProg.c -o firstProg.exe glut32.lib -lopengl32 -lglu32


The error is as follows (taken from the cmd):



C:\Users\Dylan\AppData\Local\Temp\cciCuMP6.o:firstProg.c:(.text+0x1c): undefined
reference to `__glutInitWithExit'
C:\Users\Dylan\AppData\Local\Temp\cciCuMP6.o:firstProg.c:(.text+0x37): undefined
reference to `__glutCreateWindowWithExit'
C:\Users\Dylan\AppData\Local\Temp\cciCuMP6.o:firstProg.c:(.text+0x52): undefined
reference to `__glutCreateMenuWithExit'
C:\Users\Dylan\AppData\Local\Temp\cciCuMP6.o:firstProg.c:(.text+0x66): undefined
reference to `_imp__glClear'
C:\Users\Dylan\AppData\Local\Temp\cciCuMP6.o:firstProg.c:(.text+0x74): undefined
reference to `_imp__glBegin'
C:\Users\Dylan\AppData\Local\Temp\cciCuMP6.o:firstProg.c:(.text+0x8c): undefined
reference to `_imp__glVertex2f'
C:\Users\Dylan\AppData\Local\Temp\cciCuMP6.o:firstProg.c:(.text+0xa4): undefined
reference to `_imp__glVertex2f'
C:\Users\Dylan\AppData\Local\Temp\cciCuMP6.o:firstProg.c:(.text+0xbc): undefined
reference to `_imp__glVertex2f'
C:\Users\Dylan\AppData\Local\Temp\cciCuMP6.o:firstProg.c:(.text+0xd4): undefined
reference to `_imp__glVertex2f'
C:\Users\Dylan\AppData\Local\Temp\cciCuMP6.o:firstProg.c:(.text+0xdb): undefined
reference to `_imp__glEnd'
C:\Users\Dylan\AppData\Local\Temp\cciCuMP6.o:firstProg.c:(.text+0xe2): undefined
reference to `_imp__glFlush'
C:\Users\Dylan\AppData\Local\Temp\cciCuMP6.o:firstProg.c:(.text+0x11f): undefine
d reference to `glutDisplayFunc'
C:\Users\Dylan\AppData\Local\Temp\cciCuMP6.o:firstProg.c:(.text+0x124): undefine
d reference to `glutMainLoop'
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: C:\Users\D
ylan\AppData\Local\Temp\cciCuMP6.o: bad reloc address 0x20 in section `.eh_frame
'
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: final link
failed: Invalid operation
collect2.exe: error: ld returned 1 exit status


Anyone here have any idea how to solve these errors? I've tried uninstalling and reinstalling MinGW as well as placing the GLUT files within the required directories again but to no avail.




C programming printing a linked list, not moving along list and crashing



I am trying to print a linked list, it is acting strangely, when it is suppose to move to the next item it will not, for instance the first item printed is "Granny Smith" and then the rest in the struct, when it goes to the next line what should be a new food is "ranny Smith" Always without the G, and most of the other details are corrupted or gibberish. Any help would be greatly appreciated.



#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define cls system("cls");
#define flush fflush(stdin)
#define pause system("pause");


struct food // Declaration of struct
{
char produce[20];
char type[20];
char soldBy[20];
float price;
int quantityInStock;
struct food *next;
};


void addPres(struct food** tip, char tokenPro[20], char tokenType[20], char tokenSold[20], float tokenFloat, int tokenInt);
void display ();
void displayMenu ();
int getChoice ();
void readDataIn();




int main()
{
int choice = 0;
int ;
struct food first;
char *saveFloat, *saveInt;
char tokenPro[20], tokenType[20], tokenSold[20], savePro[20], saveType[20], saveSold[20], j[1900];
float tokenFloat, messFloat;
int danint, tokenInt;
struct food* a = NULL;
FILE* file;

a = NULL; // sets the first item on the list to empty

//readDataIn();
do
{
choice = getChoice();//function to present choices and receive an answer
switch (choice)//switch routes the choice
{
case 1: //to enter a new node on the list
cls;
printf("Enter the produce type: ");
fgets(tokenPro, 20, stdin);
printf("Enter the type: ");
fgets(tokenType, 20, stdin);
printf("Enter the units of measurement: ");
fgets(tokenSold, 20, stdin);
printf("\nEnter the price per %s: ", &tokenSold);
scanf("%f", &tokenFloat );
printf("\nEnter the quantity in stock: ");
scanf("%i", &tokenInt );
//pause;
addPres(&a, tokenPro, tokenType, tokenSold, tokenFloat, tokenInt);
break;
case 2: //to display the linked list
display(a);

break;
case 3: //to reverse the order

if((file=fopen("AssignmentTwoInput.txt", "r")) != NULL) //opens files
{
while(fgets(j, sizeof(j), file)) //while information is being sent to j from the file
{
strcpy(savePro, strtok(j, ","));
strcpy(saveType, strtok(NULL, ","));
strcpy(saveSold, strtok(NULL, ","));
saveFloat = strtok(NULL, ",");
saveInt = strtok(NULL, "\n");
messFloat = atof(saveFloat); //ID number is assigned to token2
danint = atoi(saveInt); //converts the value token2 points to into an int (previously read in as an string)
addPres(&a, savePro, saveType, saveSold, messFloat, danint); //sends the name and ID to the function to add a person
//printf("\n %s \t %s \t %s \t %f \t %i", savePro, saveType, saveSold, messFloat, danint);
//pause;
}//end while loop
}//end if loop
printf("\nSuccessfully loaded input file\n\n\n"); //message to tell user the back was found and imported successfully
pause;
fclose(file);
break;
case 4: //to export data

break;
case 5: //option to exit

exit(0);
break;
default://error checking
printf("Please enter a valid choice.\n");
break;
}//switch loop close

}
while (choice != 5); //end menu choices


return 0;
}//end main


void addPres(struct food** tip, char tokenPro[20], char tokenType[20], char tokenSold[20], float tokenFloat, int tokenInt)
{


struct food* temp =

(struct food*) malloc(sizeof(struct food));
strcpy(temp->produce, tokenPro);
strcpy(temp->type, tokenType);
strcpy(temp->soldBy, tokenSold);
temp->price = tokenFloat;
temp->quantityInStock = tokenInt;

//printf("\n %s \t %s \t %s \t %f \t %i", temp->produce, temp->type, temp->soldBy, temp->price, temp->quantityInStock);
//pause;
if (tip == NULL) //if the tip node is empty
{
tip = temp; //tip node becomes this node
(*tip)->next = NULL; // since there are no others yet the next node will be empty
}


else
{
temp->next = tip; // reassigns the tip node to the next one
(*tip) = temp; //inserts current node as the tip
}
}

void display(struct food* c)
{
//c = first; //assigns c to the first node on the linked list
int count = 1;
struct food *temp;
temp = c;
cls;
printf("==========================================================================\n"); //prints a header to say which info is which
printf(" Item # Produce Type Sold By Price In Stock\n");
printf("==========================================================================\n");
while( c != NULL)
{
printf("%3i \t", count);
printf("%s \t", c->produce ); //prints name
printf("%s \t", c->type ); //prints name
printf("%s \t", c->soldBy); //prints name
printf("%-3.2f \t", c->price); //prints ID
printf("%i\n", c->quantityInStock); //prints ID
pause;
count = count + 1;
c = c->next; //advances to next item in the linked list

if(c == NULL)
{
printf("\n end \n"); //once end is found user is told

pause;
}
}
printf("\n done \n");
pause;
}//end display



How to determine the ordering of elements in a vector?



It seems strange, but I haven't found anything on the following problem: Given a vector x of length n, how can one construct a vector oo of length n such that x[oo[i]] (for i=1,..,n) is sorted. Requirements: only C functions in the standard library are allowed to be used and the code has to be fast (note: I'm not a C programmer but experienced in R. R has order() for this task).


I found the post here but this discusses sorting directly.




C++ Assign GradeBook



Hi and thanks in advanced. I'm working on this H.W. and I'm beginner. I keep on running on in M.S. VS Professional but keeps returning too many errors and I fix them, yet same issues not sure if what I had added to the code is wrong. The results should display its takes no more than 30 char. it should display total number of students received a grade, the average, and class average in one digit double value and GPA. Here is the code:



#include <iostream>
#include "GradeBook.h" // include definition of class GradeBook
using namespace std;

// constructor initializes courseName with string supplied as argument;
// initializes counter data members to 0
GradeBook::GradeBook(string name)
{
cout << "The Grade Book Constructor is called" << endl;
setCourseName(name); // validate and stores courseName
aCount = 0; // initialize count of A grades to 0
bCount = 0; // initialize count of B grades to 0
cCount = 0; // initialize count of C grades to 0
dCount = 0; // initialize count of D grades to 0
fCount = 0; // initialize count of F grades to 0
displayMessage();
cout << "The Grade Book," << getCourseName() << "Contains" << endl << endl < endl;
displatGradeReport(0);
cout << "*****The end of Grade Book Constructor.*****" << endl;
} // end GradeBook constructor

// function to set the course name; limits name to 25 or fewer characters
void GradeBook::setCourseName( string name )
{
if ( name.size() <= 30 ) // if name has 30 or fewer characters
courseName = name; // store the course name in the object
else // if name is longer than 30 characters
{ // set courseName to first 30 characters of parameter name
courseName = name.substr( 0, 30 ); // select first 25 characters
cerr << "Name \"" << name << "\" exceeds maximum length (30).\n"
<< "Limiting courseName to first 30 characters.\n" << endl;
} // end if...else
} // end function setCourseName

// function to retrieve the course name
string GradeBook::getCourseName()
{
return courseName;
} // end function getCourseName

// display a welcome message to the GradeBook user
void GradeBook::displayMessage()
{
// this statement calls getCourseName to get the
// name of the course this GradeBook represents
cout << "Welcome to the grade book for\n" << getCourseName() << "!\n"
<< endl;
} // end function displayMessage

// input arbitrary number of grades from user; update grade counter
void GradeBook::inputGrades()
{
int grade; // grade entered by user

cout << "Enter the letter grades." << endl;
cout << "Enter the EOF character to end input." << endl;
cout << "Use Ctl + D, or Ctl + Z)" << endl;

// loop until user types end-of-file key sequence
while ( ( grade = cin.get() ) != EOF )
{
// determine which grade was entered
switch ( grade ) // switch statement nested in while
{
case 'A': // grade was uppercase A
case 'a': // or lowercase a
++aCount; // increment aCount
break; // necessary to exit switch

case 'B': // grade was uppercase B
case 'b': // or lowercase b
++bCount; // increment bCount
break; // exit switch

case 'C': // grade was uppercase C
case 'c': // or lowercase c
++cCount; // increment cCount
break; // exit switch

case 'D': // grade was uppercase D
case 'd': // or lowercase d
++dCount; // increment dCount
break; // exit switch

case 'F': // grade was uppercase F
case 'f': // or lowercase f
++fCount; // increment fCount
break; // exit switch

case '\n': // ignore newlines,
case '\t': // tabs,
case ' ': // and spaces in input
break; // exit switch

default: // catch all other characters
cout << "****Incorrect letter grade entered.****" << endl;
cout << " Enter a new grade." << endl;
break; // optional; will exit switch anyway
} // end switch
} // end while
} // end function inputGrades

// display a report based on the grades entered by user
void GradeBook::displayGradeReport()
{
// output summary of results
// total grades
int gradeCount = aCount + bCount + cCount + dCount + fCount;
cout << "\n\nThe total number of students receive grade is" << gradeCount << endl;
cout << "Number of students who received each letter grade:"
<< "\nA: " << aCount // display number of A grades
<< "\nB: " << bCount // display number of B grades
<< "\nC: " << cCount // display number of C grades
<< "\nD: " << dCount // display number of D grades
<< "\nF: " << fCount // display number of F grades
<< endl;
} // end calculate number of grades received

// display class average
// if user entered at least one grade
if (gradeCount != 0)
{
// calculate total grades
int gradeTotal = 4 * aCount + 3 * bCount + 2 * cCount + 1 * dCount;

// set floating-point number format
cout << fixed << setprecision(1);

// compute and display class GPA with 1 digit of precision
cout << "\nThe class average is: "
<< static_cast< double > (gradeTotal) / gradeCount
<< endl << endl << endl;
} // end if
} // end function displayGradeReport
void GradeBook::displayGradeReport(int n)
{
// display summary of results
// calculate total grades
int gradeCount = aCount = bCount = cCount = dCount = fCount = n;
cout << "The total number of students receive grades is " << gradeCount << endl;
cout << "Number of students who received each letter grade:"
<< "\nA: " << aCount // display number of A grades
<< "\nB: " << bCount // display number of B grades
<< "\nC: " << cCount // display number of C grades
<< "\nD: " << dCount // display number of D grades
<< "\nF: " << fCount // display number of F grades
<< endl << endl;

// calculate total grades


// display class average
// calculate total grades
int gradeTotal = 4 * aCount + 3 * bCount + 2 * cCount + 1 * dCount;

// set floating-point number format
cout << fixed << setprecision(1);

// compute and display class GPA with 1 digit of precision
if (gradeCount != 0)
{
cout << "\nThe class average is: "
<< static_cast< double > (gradeTotal) / gradeCount
<< endl << endl << endl;
}
else
{
cout << "\nThe class average is: 0.0" << endl << endl << endl;
}
} // end function displayGradeReport


Here is the .h



#include <string> // program uses C++ standard string class
using namespace std;

// GradeBook class definition
class GradeBook
{
public:
GradeBook( string ); // initialize course name
void setCourseName( string ); // set the course name
string getCourseName(); // retrieve the course name
void displayMessage(); // display a welcome message
void inputGrades(); // input arbitrary number of grades from user
void displayGradeReport(); // display report based on user input
private:
string courseName; // course name for this GradeBook
int aCount; // count of A grades
int bCount; // count of B grades
int cCount; // count of C grades
int dCount; // count of D grades
int fCount; // count of F grades
}; // end class GradeBook


And here is the file I'm executing from in the project


include // program uses C++ standard string class


using namespace std;



// GradeBook class definition
class GradeBook
{
public:
GradeBook( string ); // initialize course name
void setCourseName( string ); // set the course name
string getCourseName(); // retrieve the course name
void displayMessage(); // display a welcome message
void inputGrades(); // input arbitrary number of grades from user
void displayGradeReport(); // display report based on user input
private:
string courseName; // course name for this GradeBook
int aCount; // count of A grades
int bCount; // count of B grades
int cCount; // count of C grades
int dCount; // count of D grades
int fCount; // count of F grades
}; // end class GradeBook



Can we read a smoking.mat (dataset) in C-language?



The reason i want to read it in C is:

i want to create a mnrfit.c file/function in replacement of mnrfit.m

If it is possible, please tell me how (i have searched, alot but could not find the way)?

Once, i am able to read/load it. I will save the dataset in a linked-list (own-made)




Error with program to continue after for it reaches the for loop



When i have reached my for loop, my program crashes and I really dont know what else to do. Im making an attendance record system that will prompt the user to enter there ID. Program will search a file containing their information and search for the ID entered. After it has found it, the program should ask a series of questions. After all have completed, the loop should begin again for another student. Below is a snippet of the main code.



#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

typedef struct record {
char *fname;
char *lname;
int code;
} information;

int main (void) {
char ffname[28], flname[28], ans;
int fID, i, id_;
information array[3];
FILE *kfile;

i = 0;

char buf[150];
time_t curtime;
struct tm* loc_time;

//Getting current time of system
curtime = time (NULL);

// Converting current time to local time
loc_time = localtime (&curtime);
strftime (buf,150, "%I:%M %p.\n", loc_time);


//prints error message if file cannot be found within the system
if ((kfile = fopen("C:\\Users\\keneil\\Desktop\\information.txt","r")) == NULL) {
perror("Error while opening file");
} else {
//while the file is opened and not at the end, the strings are stored into variables which forms an array of strings
while (!feof(kfile)) {
fscanf(kfile, "%s %s %d", ffname, flname, &fID);
array[i].fname = strdup(ffname);
array[i].lname = strdup(flname);
array[i].code = fID;
i++;
}
fclose(kfile);
}

Next:
printf("Please enter your ID: ");
scanf("%d", &id_);

for (i = 0; i < 3; i++) {

//printf("\n");

printf("Are you %s %s?\n", array[i].fname, array[i].lname);
printf("[y/n only]: ");
scanf(" %c", &ans);

switch (ans){
case 'y':
if((int)buf < ((int)"08:00" )){
printf("You are early for school.");
}
else{
printf("You are late for school.");
system("cls");
}
break;
case 'n':
system ("cls");
goto Next;
break;
default:
printf("invalid answer");
}
}



getch();
return 0;
}



Append Source To Binary



Is their a way to append the source code of an executable to the file itself such that the file is still executable?


For example let's take a simple program like yes from busybox. How might I append the code in a way to the binary. Again this is a simple example, I would like to be able to do such for for a multiple file example.



#include "libbb.h"

int yes_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int yes_main(int argc UNUSED_PARAM, char **argv)
{
char **pp;

argv[0] = (char*)"y";
if (argv[1])
++argv;

do {
pp = argv;
while (1) {
fputs(*pp, stdout);
if (!*++pp)
break;
putchar(' ');
}
} while (putchar('\n') != EOF);

bb_perror_nomsg_and_die();
}



Pointer to arrays syntax



I have a question about syntax of pointer to arrays. Well we know arrays are pointers themselves so why when we point to them with another pointer (which would be a pointer to pointer) we use this syntax:



Int array[10];
Int *pointer = array;


Instead of this syntax:



Int array[10];
Int **pointer = &array;


Although i know this would be correct using malloc but why not in the normal way, is it a compiler or syntax thing or i am wrong somewhere else??




Exporting float from blender and reading in c wrong value



I am writing float values from Blender using python, then read in C. For some values I get 0. If I replace that values with numbers like 2.3 or other random numbers It works. I am using struct.pack("<ffff") to write them.


Here is example value which doesn't work:



-8.881784197001252e-16, -1.700029006457271e-15, 6.106226635438361e-16, 1.0


When I opened file in hex editor I found correct number written -8.88178E-16


How can I read correct value?




C 2d array fundamental query



Why both these print giving same memory address location?

What is the difference between (arr+1) and *(arr+1)?



int main(void){
char arr[][2] = {{0,1},{2,3}};
printf("%u\n",(arr+1));
printf("%u\n",*(arr+1));
return 0;
}



why library functions should not be used in creating an os?



I am planning to study about operating systems. I met with 2 doubts. Why we should not use library functions while creating an operating system? What is the drawback in it?




Android NDK profiler for native executable produces no data



I am using the Android NDK to build a native C/C++ binary via include $(BUILD_EXECUTABLE). I have added the android-ndk-profiler module to my Android.mk according to their instructions and added calls for monstartup and moncleanup.


Running the binary on a rooted device produces gmon.out, and everything appears to be working correctly. But running $ANDROID_NDK/toolchains/.../arm-linux-androideabi-gprof shows the headers and descriptions, but no actual data.


I know the profiler intended to be used for native shared libraries and not executables, but is it possible to make this work?




pipe causing processes to freeze



The program report launches two accessed processes. Report basically feeds accessed a list of filenames and accessed prints if they have been accessed in x days.


However, my implementation is causing accessed to freeze somehow. After running reports, nothing gets printed. When I run ps, I can see two accessed programs hanging around, not dying.


At first, I thought the method of reading from stdin was wrong in accessed, but I manually piped some filenames to it cat filenames.txt | ./accessed, and it works. So report program must be wrong.


Relevant parts of report:



if (!(pid_A1 = fork())) {
char *num_arg = NULL;
size_t arg_sz = 16;
num_arg = (char *) malloc(arg_sz * sizeof(char));
snprintf(num_arg, arg_sz, "%d", cmd_args->num);

close(pipe_RtoA1[1]);
dup2(pipe_RtoA1[0], 0);
close(pipe_RtoA1[0]);

execl("accessed", "accessed", num_arg, (char *)0);
} else if (!(pid_A2 = fork())) {
char *num_arg = NULL;
size_t arg_sz = 16;
num_arg = (char *) malloc(arg_sz * sizeof(char));
snprintf(num_arg, arg_sz, "%d", -(cmd_args->num));

close(pipe_RtoA2[1]);
dup2(pipe_RtoA2[0], 0);
close(pipe_RtoA2[0]);

execl("accessed", "accessed", num_arg, (char *) 0);
} else {
FILE *fRtoA1 = NULL;
FILE *fRtoA2 = NULL;
fRtoA1 = fdopen(pipe_RtoA1[1], "w");
fRtoA2 = fdopen(pipe_RtoA2[1], "w");
close(pipe_RtoA1[0]);
close(pipe_RtoA2[0]);
fprintf(fRtoA1, "%s", file_paths);
fprintf(fRtoA2, "%s", file_paths);
}


Relevant parts of accessed:



char **process_input()
{
char **file_paths = NULL;
char *input_str = NULL;
size_t len = 0;
size_t file_paths_sz = 10;
unsigned int fcnt = 0;
long read = 0;
char delim[] = " ";

if ((file_paths = (char **) malloc(file_paths_sz * sizeof(char *))) == NULL) {
exit_program("malloc for file_paths failed.");
}

while((read = getline(&input_str, &len, stdin)) != EOF) { //FREEZES HERE
char *tmp_string = NULL;
strip_token(input_str);

tmp_string = strtok(input_str, delim);
*(file_paths + fcnt) = (char *) malloc(sizeof(char) * (strlen(tmp_string) + 1));
strncpy(*(file_paths + fcnt), tmp_string, strlen(tmp_string) + 1);
strip_token(*(file_paths + fcnt));
fcnt++;

while ((tmp_string = strtok(NULL, delim))) {
*(file_paths + fcnt) = (char *) malloc(sizeof(char) * (strlen(tmp_string) + 1));
strncpy(*(file_paths + fcnt), tmp_string, strlen(tmp_string) + 1);
strip_token(*(file_paths + fcnt));
if ((fcnt + 1) == file_paths_sz) {
file_paths_sz *= 2;
file_paths = realloc(file_paths, file_paths_sz * sizeof(char *));
}
fcnt++;
}
}

return file_paths;
}


I attached gdb to the frozen accessed processes and it seems that it is frozen at the while loop getline. So I changed the while loop to a single getline statement and it suddenly works. However, I need to read stdin until EOF. Any help on the possible sources of errors is very much appreciated. This is causing me much headache.




How to Read and Compare string in a file then get the number/s beside it in C



This is the Algorithm:



  1. Open the file.

  2. Read a string from the file.

  3. Compare the string.

    • If the string matches, get the number/s after '=', then exit the loop.



  4. Check the end of the file.

    • If it's not yet the end of the file, go back to step 2.

    • If the end of the file is met exit the loop, and go to step 5.



  5. The string is not in the file.


This is the program i made:



FILE *fp = fopen("Converter.txt", "r");

while( fgets(line, sizeof(line), fp) != NULL ){
if(strcmp(line,a)){
printf("There is such file");
sscanf(line,"%*[^=]=%f", &num);
printf("\n\n%.2f",num);
}else{
printf("NULL\n");
continue;
}break;
}


The problem is it only scan the first line and it doesn't scan the number beside the string that it compares.


Thanks.




Suppressing user defined function output?



Here is the bit of my program that is causing me this grief:



float pcRRV(){ //calculate power consumption with rated resistor values
int i;
float pr=0,ptemp; //pr=power with rated values, ptemp=temporary power variable for for() loop
for(i=0;i<=RMAX;i++){
R=RRV[i];
ptemp=(V*V)/R; //power= V^2/R
pr=ptemp+pr; //add all power values (could also have added all resistors then calculated total power, either would require for() loop)
}
printf("Given the rated resistor values, the power consumed by the resistors, in series with a %dV source, is %fW.\n",V,pr);
puts("");
return pr; //need power value for part D
}
float pcARV(){ //calculate power consumption with actual resistor values
int i;
float pa=0,ptemp; //same formate as previous function
for(i=0;i<=RMAX;i++){
A=ARV[i];
ptemp=(V*V)/A;
pa=ptemp+pa;
}
printf("Given the actual resistor values, the power consumed by the resistors, in series with a %dV source, is %fW.\n",V,pa);
puts("");
return pa;
}

float powerpercentdif(){ //calculate percent difference between two power consumption values
float a,b;
float powerdif,powerave,percentdif;
a=pcRRV(); //use return value of pcRRV() as variable
b=pcARV(); //use return value of pcARV() as variable
powerdif=(a-b);
powerave=(a+b)/2;
percentdif=(powerdif/powerave)*100;
printf("The percent difference between the power consumption given the rated values and given the actual values of the resistors is %f%%.\n",percentdif);
}


So I have these 3 user defined functions, pcRRV(), pcARV(), and powerpercentdif(). in my main function I call all 3 in the order that you see, and the output should be as follows:



Given the rated resistor values, the power consumed by the resistors, in series with a 10V source, is 66.240997W.

Given the actual resistor values, the power consumed by the resistors, in series with a 10V source, is 64.273056W.

The percent difference between the power consumption given the rated values and given the actual values of the resistors is 3.015677%.


But what actually happens is this:



Given the rated resistor values, the power consumed by the resistors, in series with a 10V source, is 66.240997W.

Given the actual resistor values, the power consumed by the resistors, in series with a 10V source, is 64.273056W.

Given the rated resistor values, the power consumed by the resistors, in series with a 10V source, is 66.240997W.

Given the actual resistor values, the power consumed by the resistors, in series with a 10V source, is 64.273056W.

The percent difference between the power consumption given the rated values and given the actual values of the resistors is 3.015677%.


Now I don't want the output of the first two functions to be displayed twice. The easiest approach would be to not call the first two functions in main, but let their outputs be displayed when the 3rd function calls them. However, since this is for a class, one of the requirements is that the 3 functions I wrote must all be called in the main function to display their output, so I have to call all 3, but I don't want the output twice. Ultimately I'm wondering how to suppress the output of the 1st and 2nd functions when I assign them to variables in the 3rd function, because I just want to use their return values in that function, not have them display their full output. Thank you for the help in advance, and when I get a reply with a super simple answer I will be a combination of relieved/angry/depressed/happy. (I've been at this for a while) Thank you!




Unhandled exception... Access Violation reading location



I'm following a tutorial on using NVIDIA/CUDA/etc. here: http://ift.tt/1N4nufK


I'm trying to add two vectors in parallel, but I am having trouble with these memory access violations mentioned in the title of my post.


The error is occurring at my printf line (I will post my code below), but if I comment it out I get taken to a file named "dbgheap.c" and I just get the same error message on line 1696 of that file (the file has 3268 lines)


The line is:



if (*pb++ != bCheck)


and the function that is in is:



extern "C" static int __cdecl CheckBytes(
unsigned char * pb,
unsigned char bCheck,
size_t nSize
)
{
while (nSize--)
{
if (*pb++ != bCheck) //this is the line with the error
{
return FALSE;
}
}
return TRUE;
}


And the memory address location it says it can't access, I believe, are the locations of my "a", "b", and "c" variables (will post my code below).


So without further adieu, here is my code (sorry there are no comments):



#include "cuda_runtime.h"
#include "device_launch_parameters.h"

#include <stdio.h>
#include <stdlib.h>

#define N 10

__global__ void kernel() {
}

__global__ void add(int *a, int *b, int *c) {
c[blockIdx.x] = a[blockIdx.x] + b[blockIdx.x];
}

void random_ints(int* a,int num) {
for (int i = 0; i<num; i++)
a[i] = rand();
}

int main () {
int *a,*b,*c;
int *dev_a, *dev_b, *dev_c;
int size = N*sizeof(int);

cudaMalloc((void**)&dev_a,size);
cudaMalloc((void**)&dev_b,size);
cudaMalloc((void**)&dev_c,size);

a = (int*)malloc(size);
b = (int*)malloc(size);
c = (int*)malloc(size);

random_ints(a,N);
random_ints(b,N);



cudaMemcpy(dev_a,&a,size,cudaMemcpyHostToDevice);
cudaMemcpy(dev_b,&b,size,cudaMemcpyHostToDevice);
add<<<N,1>>>(dev_a,dev_b,dev_c);

cudaMemcpy(&c,dev_c,size,cudaMemcpyDeviceToHost);

for (int i = 0; i<N; i++)
printf("%d + %d = %d\n",a[i],b[i],c[i]);

free(a); free(b); free(c);
cudaFree(dev_a);
cudaFree(dev_b);
cudaFree(dev_c);
return 0;
}


If you need any clarifications just ask.


Thanks!




C socket read() return value



I'm working on a C project to send a file from one IP address to another, using a server/client structure. From reading other posts, I understand that reading from a socket will return 0 only if the socket is closed.


Relevant code on server side (socket(), bind(), and accept() behave as expected)



char *toSend = malloc(packet_size);
size_t bytesRead;
while ((bytesRead = fread(toSend, sizeof(char), packet_size, fp)) > 0) {
printf("Sending: %s \n", toSend);
write(newsockfd, toSend);
usleep(packet_delay*1000000);
}


On client side:



char buffer[256];
int numRead;
while ((numRead = read(sockfd, buffer, 255)) > 0) {
printf("read %d\n", numRead);
printf("%s\n", buffer);
fwrite(buffer, sizeof(char), 255, fp);
}


The client connect() call returns 0 for success, but the first call to read(sockfd, buffer, 255) returns 0, despite the socket being open at the time; this seems like it shouldn't be possible. Does anyone have some tips? Thank you.




Beginner C Programmer in Need of Assistance with Creating a Letter Pyramid



I'm just learning how to start programming with C, and I'm stumped on this question. My code compiles, and it works initially, but it won't print after the initial prompt of asking the user to input a letter. Here is what my code currently looks like



intmain(void
{
char letter = 'A';
char display;
char output;
int row;
char spaces = ' ';

printf ("Please enter a lowercase letter!");
scanf ("%c", &letter);

while ((letter < 96) || (letter > 122))
{
printf ("That's not lowercase.");
scanf ("%c", &letter);
}

else if ((letter > 96) || (letter < 122))
{
while (1)
{
letter = letter - 32;
printf ("%c", letter -1);
printf("\n\n");
spaces = letter - 1;
putchar = (spaces);
letter++
spaces++
}
}

return 0;
}
}


The end result should be this for example. Say that the user entered E:


----------A


---------ABA


--------ABCBA


-------ABCDCBA


------ABCDEDCBA


So, the letter entered would be the center letter on the bottom of the pyramid.




Are there any differences between indirection and Dereferencing when they access the value of a pointer in C?



I am a but confused about how to access the content of a memory location pointed by a pointer.


My question is: Are there any differences between indirection and Dereferencing when they access the value of a pointer in C?




Convert double* to float*



I am wondering what how to convert double* to float*, and float* to double* in C or C++? Thanks. I tried cast using (float*) and (double*), but it seems not working as far as my observation.




convert binary file to hexadecimal characters



How do I convert the contents of a binary file into hexadecimal?


ex. test.bin contains



abcdefghijklmn in binary


Convert contents to output.txt which will contain



61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e



fgetws segfaults after a few iterations



I'm trying to create a container that holds the Japanese alphabet, so I'm using the data type wchar_t, and have my .c and .txt files encoded in UTF-8. The idea is that the program populates the container by reading in the .txt file. I can read in the first few lines, but after a few iterations the program segfaults. I suspect it is fgetws because of a few wprintf statements that I've put around the function.



#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#include <locale.h>

typedef struct entry {
wchar_t romaji[5];
} entry;

typedef struct dictionary {
struct entry entry[46];
} dictionary;

void init_dictionary(dictionary **dictionary) {
(*dictionary) = malloc(sizeof(dictionary));
}

void add_romaji(dictionary *dictionary, wchar_t *romaji, int index) {
entry new;

wcscpy(new.romaji, romaji);

dictionary->entry[index] = new;
}

void populate(dictionary *dictionary) {
FILE *fp;
wchar_t line[5];
wchar_t *ptr;
wchar_t romaji[5];
int i;

fp = fopen("romaji.txt", "r");
i = 0;

while(fgetws(line, 5, fp) != NULL) {
wcstok(line, L"\n", &ptr);
wcscpy(romaji, line);
add_romaji(dictionary, romaji, i);
++i;
}

fclose(fp);
}

int main(int argc, char ** argv) {
setlocale(LC_CTYPE, "");

dictionary *dictionary;

init_dictionary(&dictionary);
populate(dictionary);

return EXIT_SUCCESS;
}


romaji.txt is in UTF-8, and just contains a line for each character in the Japanese alphabet. I'm unable to get the indentation here to work, so I cannot post it, sorry. I tried searching for an answer, but none have helped. If anyone could let me know what my mistake is, I would appreciate it.




Code::Blocks Process terminated with status 255 (0 minute(s), 24 second(s))



I use win7 and while working on glut project with given example main CPP it tries to process a windows appears and suddenly it says "Windows has stopped working"


And Code::Block displays -Process terminated with status 255 (0 minute(s), 24 second(s))


I am using freeglut with libfreeglut.a to link libraries.


Additional Information: Checking for existence: C:\Program Files\CodeBlocks\program\example\bin\Debug\example.exe Executing: "C:\Program Files\CodeBlocks/cb_console_runner.exe" "C:\Program Files\CodeBlocks\program\example\bin\Debug\example.exe" (in C:\Program Files\CodeBlocks\MinGW\freeglut\bin




Pages getting (deleted) when using shmget and shmat



I wrote the following 2 test programs, one that uses shmat and another that uses shmget and execve's the first binary.


The code is as follows :-



int main(int argc, char **argv) {
void *retval;
long shmid = atol(argv[1]);

retval = shmat(shmid, NULL, SHM_RDONLY);
printf("%p\n", retval);
}


And the wrapper file,



int setupshm(char *name) {
int shmid;
shmid = shmget(IPC_PRIVATE, 100, IPC_CREAT|0666);
return shmid;
}

int main() {

int pid = fork();
if (pid == 0) {
char **envp = NULL;
char *argv[3];
char num[10];

sprintf(num, "%d", setupshm("whatever"));

argv[1] = "./test";
argv[2] = num;
argv[3] = NULL;

execve("./test", argv, envp);
}

else { int status; wait(pid, &status, 0); }
}


I run the wrapper program in gdb, intercept the execve, debug the test program, see that shmget succeeds; then inspect its /proc/pid/maps and I see that the page corresponding to the shmget shows up as "(Deleted)". Why does this happen? What am I doing wrong?




Why do we need to declare functions before using them in C?



In C99, the compiler will issue a warning if a function is called before its declaration. For example, this will cause a warning:



int sum(const int k) {
return accsum(k, 0);
}


int accsum(const int k, const int acc) {
if (k == 0) {
return acc;
} else {
return accsum(k-1, k + acc);
}
}

int main() {
int x = sum(3);
return 0;
}


The answer I've seen after Googling is declaration is needed so that the compiler can check the parameter types to avoid errors. But why can't the compiler just go find the function definition of accsum before executing accsum when accsum is called from within sum?




GTK3 CSS colors not respected - even in official example



I've been suffering with a simple task: I want to make a GtkLabel's background and text another color. I've read many pages, and as such also tried to put an EventBox behind the label and changeing the box's bg color instead. All to no avail.


Then I came across this tutorial, which I copied, compiled without change, and it has the same problem: The background isn't yellow, and the text isn't blue, as they are supposed to be. I even tried replacing the 'yellow' color by rgba(1, 0.5, 0.5, 1) to be sure there was no transparency.


An extra fact: The font is being changed correctly! So the CSS is really being interpreted.


So, why doesn't this work? (I've come across another user with the exactly same problem - no solution though).


Suspecting: is it possible that the theme is somehow blocking later changes? I would suppose that later defined CSS should override any theme definition?


Note: I'm using gtk 3.12.2




Why arbitrary expressions can't be used as an array size, e.g. int[0,1]?



Ignoring static and * (for an omitted size) in between the [] brackets, the syntax for an array declarator is (from C99 TC3 (n1256) 6.7.5 p1; C11 (n1570) 6.7.6 p1):



direct-declarator: direct-declarator [ type-qualifier-listopt assignment-expressionopt ] [...]



Thus, a declaration like



int foo[0,1];


is a syntax error, but



int foo[(0,1)];


is allowed (at block scope, as this is a VLA).


There are certain cases where arbitrary expressions aren't allowed because this would cause ambiguity with comma used as a separator. For example, the arguments of a function call must be assignment expressions. I don't see, however, how such an ambiguity could be caused by


direct-declarator: direct-declarator [ type-qualifier-listopt expressionopt ]


Would this define a strict superset of the C language? Are there examples where this grammar is ambiguous?


C89*) required a constant expression in the syntax (which is a conditional expression) so this needed to be changed for C99 to allow VLAs. But I fail to see why it was changed to an assignment expression rather than to an expression. Is there any technical reason?


Gcc (and perhaps other compilers) had VLAs as an extension before they were added to the C standard, a conflict with some other extension could also be an explanation, but I'm not aware of such an extension. Gcc 3.0.4 accepts int a[0,1]; (with -std=gnu89 and -traditional), newer versions (tested with Gcc (Debian) 4.7.2-5) don't, so this looks unlikely to be the cause.


As far as I can see, this question equivalently applies to direct abstract declarators in type names.


*) According to this C89 draft, 3.5.4.




creating threads using pthread.c



I am trying to learn how to create threads in c using the pthread library, I am using the following code:



#include <stdlib.h>
#include <stdio.h>
#include <semaphore.h>
#include <pthread.h>


static int glob = 0;
static sem_t sem;


static void *threadFunc(void *arg) {

int loops = *((int *) arg);
int loc, j;

for (j = 0; j < loops; j++) {

if (sem_wait(&sem) == -1)
exit(2);

loc = glob;
loc++;
glob = loc;

if (sem_post(&sem) == -1)
exit(2);
}

printf("\n%d %d\n",glob/20,glob);
return NULL;
}



int main(int argc, char *argv[]) {

pthread_t t1, t2, t3, t4;
int s;
int loops = 20;

if (sem_init(&sem, 0, 1) == -1) {
printf("Error, init semaphore\n");
exit(1);
}

s = pthread_create(&t1, NULL, threadFunc, &loops);
if (s != 0) {
printf("Error, creating threads\n");
exit(1);
}

s = pthread_create(&t2, NULL, threadFunc, &loops);
if (s != 0) {
printf("Error, creating threads\n");
exit(1);
}

s = pthread_create(&t3, NULL, threadFunc, &loops);
if (s != 0) {
printf("Error, creating threads\n");
exit(1);
}

s = pthread_create(&t4, NULL, threadFunc, &loops);
if (s != 0) {
printf("Error, creating threads\n");
exit(1);
}

s = pthread_join(t1, NULL);
if (s != 0) {
printf("Error, creating threads\n");
exit(1);
}

s = pthread_join(t2, NULL);
if (s != 0) {
printf("Error, creating threads\n");
exit(1);
}

s = pthread_join(t3, NULL);
if (s != 0) {
printf("Error, creating threads\n");
exit(1);
}

s = pthread_join(t4, NULL);
if (s != 0) {
printf("Error, creating threads\n");
exit(1);
}

printf("glob value %d \n", glob);
exit(0);
}


What are the expected values of glob when I try to print them using the print statement in threadFunc? Shuold they be 20,40,60 and 80? When I execute the above program I get different values for glob like, 61, 50, 73 and 80!! or 29,76,78,80? How come? EVerytime I execute I get different values for glob. I think it has something to do with the semaphore but then how can the value for glob decrease like in the first output example I gave you?


Furthermore, what is the purpose for a thread_initiate given to pthread_create? Not threadFunc specifically but in general what do programmers dealing with threads in c generally do using the thread_initiate function passed to pthread_create?




Iterating on files of a folder, with specific condition



Using this solution with dirent.h, I'm trying to iterate on specific files of the current folder (those which have .wav extension and begin with 3 digits) with the following code :


(Important note: as I use MSVC++ 2010, it seems that I cannot use import <regex>, and that I cannot use http://ift.tt/1AHliFQ as well because no C+11 support)



DIR *dir;
struct dirent *ent;
if ((dir = opendir (".")) != NULL) {
while ((ent = readdir (dir)) != NULL) {
printf ("%s\n", ent->d_name);
//if substr(ent->d_name, 0, 3) ... // what to do here to
// check if those 3 first char are digits?
// int i = susbtr(ent->d_name, 0, 3).strtoi(); // error here! how to parse
// the 3 first char (digits) as int?

// if susbtr(ent->d_name, strlen(ent->d_name)-3) != "wav" // ...

}
closedir (dir);
} else {
perror ("");
return EXIT_FAILURE;
}



C check if last character of string is equal with X



im writing a sketch for my arduino and i would like to check the last character of my string.


For example:


If the input is cats- i want to see if the last char (in my case is "-") is actualy -


The code im using:


The serial event function



void serialEvent() {
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
// add it to the inputString:
inputString += inChar;
// if the incoming character is a newline, set a flag
// so the main loop can do something about it:
if (inChar == '.') {
stringComplete = true;
}
}
}


This is checking if the input string is completed by checking the input is equals with -. However this is working only with the console because the python script im using is sending everything together



void loop() {
if (stringComplete) {
Serial.println(inputString);
display.clearDisplay();
display.setTextSize(1);
display.setCursor(0,0);
display.println("Altitude:");
display.println(inputString);
display.display();
// clear the string:
inputString = "";
stringComplete = false;
}


Any idea on how to check it?




return all the values in a function



This is probably an easy one but my brain is fried from all this. For the function below i want to return all the rocks that are equal to 2 and not just the first one. This just prints the first rock thats equal to 2 it finds. Thanks in advance



void view_drilled_rocks()
{
int i;
for (i=0;i<totalRocks;i++){
if (rocks[i].rock_completed==2){
printf("Rock No. Geoligist Drill(Y/N) Due date or comp date\n");
printf("%d \t %s \t %d \t%s", rocks[i].rock_rover_number, rocks[i].geoligist, rocks[i].rock_completed , rocks[i].due_date);
return 0;
}
}

}



Playing with shmat and shm_open



I just read the manpages for shm_open and shmat and was trying out the following example. In a file test.c I do,



int main(int argc, char **argv) {
void *retval;
long shmid = atol(argv[1]);

retval = shmat(shmid, NULL, SHM_RDONLY);
printf("%p\n", retval);
}


And in a wrapper file I do,



int setupshm(char *name) {
int shmid;
shmid = shm_open(name, O_CREAT|O_RDWR, 0666);
return shmid;
}

int main() {
char **envp = NULL;
char *argv[3];
char num[10];

sprintf(num, "%d", setupshm("whatever"));

argv[1] = "./test";
argv[2] = num;
argv[3] = NULL;

execve("./test", argv, envp);
}


I tried adding in a strerror(errno) at test.c and I get Identifier removed. What does that mean? What am I doing wrong? Given a shared memory identifier(shmid), shouldn't I be able to access the shared memory from any process?




Guidelines/ Tips for programming a C UDP Library to implement basic functions? ( socket , bind , connect)



Any Guide/ Tips for programming a C UDP library to implement the socket, bind, connect functions correctly?




How can I read from a file and store the contents in separate variables?



So, I've already search this site to see if there was any question similar to mine and I came up empty-handed. Here's the setup. I used my program to write to a file and I stored the contents within a record (using arrays). The problem is that I can't seem to find a way to search the array of records for a specific code and manipulate whatever that is linked to that code. Here is a snippet of my program:



  • Case 4 is where I print to the Stock.txt file and read the contents into variables.

  • Case 5 is where I try to search the array using typedef for a code and printing what relates to the code.


I would like to know how to properly execute case 5.



case 4: ;
FILE *kfile ;
//opens the file called kfile found from the path below.
kfile= fopen("Stock.txt","w");

//prompts the programmer to enter a command to end the input of records.
printf("CTRL+Z' to end input\n");
printf("===========================================");
printf("\nUSE A SINGLE APACE BETWEEN EACH WORD/NUMBER");
printf("\n===========================================\n\n");
//while it is not the end of file, programmer still enters records of persons.

printf("Enter Code(MAX 3 letters), Item Name, Quantity, Price: \n");
scanf("%s %s %d %d", filecode, itemname, &quantity, &fileprice);
while (!feof(stdin) ){
fprintf(kfile,"%s\t%s \t%d\t%d\n", filecode, itemname, quantity, fileprice);
//prints to the file
printf("Enter Code(MAX 3 letters), Item Name, Quantity, Price: \n");
scanf("%s %s %d %d", filecode, itemname, &quantity, &fileprice);
}
fclose(kfile);
break;

case 5: ;
FILE *mfile;
if ((mfile = fopen("Stock.txt","r")) == NULL) {
perror("Error while opening file");
}else {
while (!feof(mfile)) {
fscanf(mfile, "%s\t%s \t%d\t%d", filecode, itemname, &quantity, &fileprice);
array[x].itemname1 = strdup(itemname);
array[x].code1 = strdup(filecode);
array[x].quantity1 = quantity;
array[x].price1 = fileprice;
}
fclose(mfile);
}

printf("Please enter Code: ");
scanf("%s", &codenew);
printf("\n");
printf("\nCode\tItem Name\tQuantity\tPrice\n");
for (x = 1; x <= 100; x++) {
if (strcmp(array[x].code1, codenew)==0) {
// print the record
printf("%s\t%s \t%d\t\t%d\n", array[x].code1,array[x].itemname1, array[x].quantity1,array[x].price1);

}
}
break;



Converting 2d array C code to malloc



I made a program that adds two matrices and displays their sum with a max dimension of 100.



/* This program asks the user for 2 matrices called A and B, as integers,
and displays their sum, C. The max dimension of each matrix is 100. */

#include <stdio.h>

// Construct function
void construct()
{
int m, n, i, j; // Variables
int first[100][100], second[100][100], sum[100][100]; // Matrices variables

printf("Please enter the number of rows: ");
scanf("%d", &m);
printf("Please enter the number of columns: ");
scanf("%d", &n);

// User enters m x n amount whole numbers for the Matrix A
printf("Enter Matrix A\n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &first[i][j]);

// User enters m x n amount whole numbers for the Matrix B
printf("Enter Matrix B\n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &second[i][j]);

// Adds the sum of Matrix A and Matrix B
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
sum[i][j] = first[i][j] + second[i][j];

// Display the sum of Matrix A and Matrix B
printf("A + B =\n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
printf("%d ", sum[i][j]);

printf("\n"); // Prints new line
}

return ;
}

// Main Function
int main()
{
construct(); // Calls construct function
return 0;
}


Now I need to change it so there is no max size for each matrix. So I need to use malloc to create my arrays. So I cant use int A[rows][cols]. This is what I did to covert arrays to malloc. It compiles but it crashes after I entered all the integers. Need help.



/* This program asks the user for 2 matrices called A and B, as integers,
and displays their sum, C. The max dimension of each matrix is 100. */

#include <stdio.h>
#include <stdlib.h>

// Construct function
void construct()
{
int m, n, i, j; // Variables
int *first = NULL;
int *second = NULL;
int *sum = NULL; // Matrices variables

printf("Please enter the number of rows: ");
scanf("%d", &m);
printf("Please enter the number of columns: ");
scanf("%d", &n);

first = (int*)malloc(m * sizeof(int));
second = (int*)malloc(n * sizeof(int));
sum = (int*)malloc(m * n * sizeof(int));


// User enters m x n amount whole numbers for the Matrix A
printf("Enter Matrix A\n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &first);

// User enters m x n amount whole numbers for the Matrix B
printf("Enter Matrix B\n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &second);

// Adds the sum of Matrix A and Matrix B
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
sum = *first + *second;

// Display the sum of Matrix A and Matrix B
printf("A + B =\n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
printf("%d ", sum);

printf("\n");
}

return ;
}

// Main Function
int main()
{
construct(); // Calls construct function
return 0;
}