Search Results

Search found 122 results on 5 pages for 'c99'.

Page 5/5 | < Previous Page | 1 2 3 4 5 

  • Misaligned Pointer Performance

    - by Elite Mx
    Aren't misaligned pointers (in the BEST possible case) supposed to slow down performance and in the worst case crash your program (assuming the compiler was nice enough to compile your invalid c program). Well, the following code doesn't seem to have any performance differences between the aligned and misaligned versions. Why is that? /* brutality.c */ #ifdef BRUTALITY xs = (unsigned long *) ((unsigned char *) xs + 1); #endif ... /* main.c */ #include <stdio.h> #include <stdlib.h> #define size_t_max ((size_t)-1) #define max_count(var) (size_t_max / (sizeof var)) int main(int argc, char *argv[]) { unsigned long sum, *xs, *itr, *xs_end; size_t element_count = max_count(*xs) >> 4; xs = malloc(element_count * (sizeof *xs)); if(!xs) exit(1); xs_end = xs + element_count - 1; sum = 0; for(itr = xs; itr < xs_end; itr++) *itr = 0; #include "brutality.c" itr = xs; while(itr < xs_end) sum += *itr++; printf("%lu\n", sum); /* we could free the malloc-ed memory here */ /* but we are almost done */ exit(0); } Compiled and tested on two separate machines using gcc -pedantic -Wall -O0 -std=c99 main.c for i in {0..9}; do time ./a.out; done

    Read the article

  • Perl missing while installing nginx on centos

    - by Ahoura Ghotbi
    I am trying to install nginx on my server, however it keeps returning "./configure: error: perl 5.6.1 or higher is required" eventhough I have perl v5.8.8!!!! I have already downloaded perl and trying to configure it using the following command : ./configure --with-http_stub_status_module --with-http_perl_module --with-http_flv_module --add-module=nginx_mod_h264_streaming here is the output : [root@fst nginx-0.8.55]# ./configure --with-http_stub_status_module --with-http_perl_module --with-http_flv_module --add-module=nginx_mod_h264_streaming checking for OS + Linux 2.6.18-308.el5 x86_64 checking for C compiler ... found + using GNU C compiler + gcc version: 4.1.2 20080704 (Red Hat 4.1.2-52) checking for gcc -pipe switch ... found checking for gcc builtin atomic operations ... found checking for C99 variadic macros ... found checking for gcc variadic macros ... found checking for unistd.h ... found checking for inttypes.h ... found checking for limits.h ... found checking for sys/filio.h ... not found checking for sys/param.h ... found checking for sys/mount.h ... found checking for sys/statvfs.h ... found checking for crypt.h ... found checking for Linux specific features checking for epoll ... found checking for sendfile() ... found checking for sendfile64() ... found checking for sys/prctl.h ... found checking for prctl(PR_SET_DUMPABLE) ... found checking for sched_setaffinity() ... found checking for crypt_r() ... found checking for sys/vfs.h ... found checking for nobody group ... found checking for poll() ... found checking for /dev/poll ... not found checking for kqueue ... not found checking for crypt() ... not found checking for crypt() in libcrypt ... found checking for F_READAHEAD ... not found checking for posix_fadvise() ... found checking for O_DIRECT ... found checking for F_NOCACHE ... not found checking for directio() ... not found checking for statfs() ... found checking for statvfs() ... found checking for dlopen() ... not found checking for dlopen() in libdl ... found checking for sched_yield() ... found checking for SO_SETFIB ... not found configuring additional modules adding module in nginx_mod_h264_streaming + ngx_http_h264_streaming_module was configured checking for PCRE library ... found checking for system md library ... not found checking for system md5 library ... not found checking for OpenSSL md5 crypto library ... found checking for zlib library ... found checking for perl + perl version: v5.8.8 built for x86_64-linux-thread-multi ./configure: error: perl 5.6.1 or higher is required

    Read the article

  • Solaris 11.2: Functional Deprecation

    - by alanc
    In Solaris 11.1, I updated the system headers to enable use of several attributes on functions, including noreturn and printf format, to give compilers and static analyzers more information about how they are used to give better warnings when building code. In Solaris 11.2, I've gone back in and added one more attribute to a number of functions in the system headers: __attribute__((__deprecated__)). This is used to warn people building software that they’re using function calls we recommend no longer be used. While in many cases the Solaris Binary Compatibility Guarantee means we won't ever remove these functions from the system libraries, we still want to discourage their use. I made passes through both the POSIX and C standards, and some of the Solaris architecture review cases to come up with an initial list which the Solaris architecture review committee accepted to start with. This set is by no means a complete list of Obsolete function interfaces, but should be a reasonable start at functions that are well documented as deprecated and seem useful to warn developers away from. More functions may be flagged in the future as they get deprecated, or if further passes are made through our existing deprecated functions to flag more of them. Header Interface Deprecated by Alternative Documented in <door.h> door_cred(3C) PSARC/2002/188 door_ucred(3C) door_cred(3C) <kvm.h> kvm_read(3KVM), kvm_write(3KVM) PSARC/1995/186 Functions on kvm_kread(3KVM) man page kvm_read(3KVM) <stdio.h> gets(3C) ISO C99 TC3 (Removed in ISO C11), POSIX:2008/XPG7/Unix08 fgets(3C) gets(3C) man page, and just about every gets(3C) reference online from the past 25 years, since the Morris worm proved bad things happen when it’s used. <unistd.h> vfork(2) PSARC/2004/760, POSIX:2001/XPG6/Unix03 (Removed in POSIX:2008/XPG7/Unix08) posix_spawn(3C) vfork(2) man page. <utmp.h> All functions from getutent(3C) man page PSARC/1999/103 utmpx functions from getutentx(3C) man page getutent(3C) man page <varargs.h> varargs.h version of va_list typedef ANSI/ISO C89 standard <stdarg.h> varargs(3EXT) <volmgt.h> All functions PSARC/2005/672 hal(5) API volmgt_check(3VOLMGT), etc. <sys/nvpair.h> nvlist_add_boolean(3NVPAIR), nvlist_lookup_boolean(3NVPAIR) PSARC/2003/587 nvlist_add_boolean_value, nvlist_lookup_boolean_value nvlist_add_boolean(3NVPAIR) & (9F), nvlist_lookup_boolean(3NVPAIR) & (9F). <sys/processor.h> gethomelgroup(3C) PSARC/2003/034 lgrp_home(3LGRP) gethomelgroup(3C) <sys/stat_impl.h> _fxstat, _xstat, _lxstat, _xmknod PSARC/2009/657 stat(2) old functions are undocumented remains of SVR3/COFF compatibility support If the above table is cut off when viewing in the blog, try viewing this standalone copy of the table. To See or Not To See To see these warnings, you will need to be building with either gcc (versions 3.4, 4.5, 4.7, & 4.8 are available in the 11.2 package repo), or with Oracle Solaris Studio 12.4 or later (which like Solaris 11.2, is currently in beta testing). For instance, take this oversimplified (and obviously buggy) implementation of the cat command: #include <stdio.h> int main(int argc, char **argv) { char buf[80]; while (gets(buf) != NULL) puts(buf); return 0; } Compiling it with the Studio 12.4 beta compiler will produce warnings such as: % cc -V cc: Sun C 5.13 SunOS_i386 Beta 2014/03/11 % cc gets_test.c "gets_test.c", line 6: warning: "gets" is deprecated, declared in : "/usr/include/iso/stdio_iso.h", line 221 The exact warning given varies by compilers, and the compilers also have a variety of flags to either raise the warnings to errors, or silence them. Of couse, the exact form of the output is Not An Interface that can be relied on for automated parsing, just shown for example. gets(3C) is actually a special case — as noted above, it is no longer part of the C Standard Library in the C11 standard, so when compiling in C11 mode (i.e. when __STDC_VERSION__ >= 201112L), the <stdio.h> header will not provide a prototype for it, causing the compiler to complain it is unknown: % gcc -std=c11 gets_test.c gets_test.c: In function ‘main’: gets_test.c:6:5: warning: implicit declaration of function ‘gets’ [-Wimplicit-function-declaration] while (gets(buf) != NULL) ^ The gets(3C) function of course is still in libc, so if you ignore the error or provide your own prototype, you can still build code that calls it, you just have to acknowledge you’re taking on the risk of doing so yourself. Solaris Studio 12.4 Beta % cc gets_test.c "gets_test.c", line 6: warning: "gets" is deprecated, declared in : "/usr/include/iso/stdio_iso.h", line 221 % cc -errwarn=E_DEPRECATED_ATT gets_test.c "gets_test.c", line 6: "gets" is deprecated, declared in : "/usr/include/iso/stdio_iso.h", line 221 cc: acomp failed for gets_test.c This warning is silenced in the 12.4 beta by cc -erroff=E_DEPRECATED_ATT No warning is currently issued by Studio 12.3 & earler releases. gcc 3.4.3 % /usr/sfw/bin/gcc gets_test.c gets_test.c: In function `main': gets_test.c:6: warning: `gets' is deprecated (declared at /usr/include/iso/stdio_iso.h:221) Warning is completely silenced with gcc -Wno-deprecated-declarations gcc 4.7.3 % /usr/gcc/4.7/bin/gcc gets_test.c gets_test.c: In function ‘main’: gets_test.c:6:5: warning: ‘gets’ is deprecated (declared at /usr/include/iso/stdio_iso.h:221) [-Wdeprecated-declarations] % /usr/gcc/4.7/bin/gcc -Werror=deprecated-declarations gets_test.c gets_test.c: In function ‘main’: gets_test.c:6:5: error: ‘gets’ is deprecated (declared at /usr/include/iso/stdio_iso.h:221) [-Werror=deprecated-declarations] cc1: some warnings being treated as errors Warning is completely silenced with gcc -Wno-deprecated-declarations gcc 4.8.2 % /usr/bin/gcc gets_test.c gets_test.c: In function ‘main’: gets_test.c:6:5: warning: ‘gets’ is deprecated (declared at /usr/include/iso/stdio_iso.h:221) [-Wdeprecated-declarations] while (gets(buf) != NULL) ^ % /usr/bin/gcc -Werror=deprecated-declarations gets_test.c gets_test.c: In function ‘main’: gets_test.c:6:5: error: ‘gets’ is deprecated (declared at /usr/include/iso/stdio_iso.h:221) [-Werror=deprecated-declarations] while (gets(buf) != NULL) ^ cc1: some warnings being treated as errors Warning is completely silenced with gcc -Wno-deprecated-declarations

    Read the article

  • Access denied error when building project in Xcode after fresh SVN checkout

    - by TheLearner
    I am seeing 2 strange access denied errors which I cant solve. This error occurs when a colleague checks out the project in SVN and it tries to find a file in my downloads folder - there is nothing in my download folder though: ProcessPCH /var/folders/f0/f01B78egHdyWY62v5MABJk+++TM/-Caches-/com.apple.Xcode.502/SharedPrecompiledHeaders/SplitView_Prefix-allviomrzhantlbahmhixtzhknpl/SplitView_Prefix.pch.gch SplitView_Prefix.pch normal armv7 objective-c com.apple.compilers.gcc.4_2 cd /SubVersion/SplitView/trunk/SplitView setenv LANG en_US.US-ASCII setenv PATH "/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin" /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc-4.2 -x objective-c-header -arch armv7 -fmessage-length=0 -pipe -std=c99 -Wno-trigraphs -fpascal-strings -O0 -Wreturn-type -Wunused-variable -isysroot /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.2.sdk -fvisibility=hidden -gdwarf-2 -mno-thumb -miphoneos-version-min=4.2 -iquote /SubVersion/SplitView/trunk/SplitView/build/SplitView.build/Debug-iphoneos/Renovatio.build/SplitView-generated-files.hmap -I/SubVersion/SplitView/trunk/SplitView/build/SplitView.build/Debug-iphoneos/Renovatio.build/SplitView-own-target-headers.hmap -I/SubVersion/SplitView/trunk/SplitView/build/SplitView.build/Debug-iphoneos/Renovatio.build/SplitView-all-target-headers.hmap -iquote /SubVersion/SplitView/trunk/SplitView/build/SplitView.build/Debug-iphoneos/Renovatio.build/SplitView-project-headers.hmap -Wno-write-strings -F/SubVersion/SplitView/trunk/SplitView/build/Debug-iphoneos -F/SubVersion/SplitView/trunk/SplitView -F/Users//Downloads -I/SubVersion/SplitView/trunk/SplitView/build/Debug-iphoneos/include -I/SubVersion/SplitView/trunk/SplitView/build/SplitView.build/Debug-iphoneos/Renovatio.build/DerivedSources/armv7 -I/SubVersion/SplitView/trunk/SplitView/build/SplitView.build/Debug-iphoneos/Renovatio.build/DerivedSources -fno-regmove -falign-loops=16 -fvisibility=default -c /SubVersion/SplitView/trunk/SplitView/SplitView_Prefix.pch -o /var/folders/f0/f01B78egHdyWY62v5MABJk+++TM/-Caches-/com.apple.Xcode.502/SharedPrecompiledHeaders/SplitView_Prefix-allviomrzhantlbahmhixtzhknpl/SplitView_Prefix.pch.gch cc1objplus: error: /Users//Downloads: Permission denied ProcessPCH++ /var/folders/f0/f01B78egHdyWY62v5MABJk+++TM/-Caches-/com.apple.Xcode.502/SharedPrecompiledHeaders/SplitView_Prefix-fdhrznnmptbkzefjexcjfecmqxmq/SplitView_Prefix.pch.gch SplitView_Prefix.pch normal armv7 objective-c++ com.apple.compilers.gcc.4_2 cd /SubVersion/SplitView/trunk/SplitView setenv LANG en_US.US-ASCII setenv PATH "/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin" /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc-4.2 -x objective-c++-header -arch armv7 -fmessage-length=0 -pipe -Wno-trigraphs -fpascal-strings -O0 -Wreturn-type -Wunused-variable -isysroot /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.2.sdk -fvisibility=hidden -fvisibility-inlines-hidden -gdwarf-2 -mno-thumb -miphoneos-version-min=4.2 -iquote /SubVersion/SplitView/trunk/SplitView/build/SplitView.build/Debug-iphoneos/Renovatio.build/SplitView-generated-files.hmap -I/SubVersion/SplitView/trunk/SplitView/build/SplitView.build/Debug-iphoneos/Renovatio.build/SplitView-own-target-headers.hmap -I/SubVersion/SplitView/trunk/SplitView/build/SplitView.build/Debug-iphoneos/Renovatio.build/SplitView-all-target-headers.hmap -iquote /SubVersion/SplitView/trunk/SplitView/build/SplitView.build/Debug-iphoneos/Renovatio.build/SplitView-project-headers.hmap -Wno-write-strings -F/SubVersion/SplitView/trunk/SplitView/build/Debug-iphoneos -F/SubVersion/SplitView/trunk/SplitView -F/Users//Downloads -I/SubVersion/SplitView/trunk/SplitView/build/Debug-iphoneos/include -I/SubVersion/SplitView/trunk/SplitView/build/SplitView.build/Debug-iphoneos/Renovatio.build/DerivedSources/armv7 -I/SubVersion/SplitView/trunk/SplitView/build/SplitView.build/Debug-iphoneos/Renovatio.build/DerivedSources -c /SubVersion/SplitView/trunk/SplitView/SplitView_Prefix.pch -o /var/folders/f0/f01B78egHdyWY62v5MABJk+++TM/-Caches-/com.apple.Xcode.502/SharedPrecompiledHeaders/SplitView_Prefix-fdhrznnmptbkzefjexcjfecmqxmq/SplitView_Prefix.pch.gch cc1objplus: error: /Users//Downloads: Permission denied

    Read the article

  • GCC: Simple inheritance test fails

    - by knight666
    I'm building an open source 2D game engine called YoghurtGum. Right now I'm working on the Android port, using the NDK provided by Google. I was going mad because of the errors I was getting in my application, so I made a simple test program: class Base { public: Base() { } virtual ~Base() { } }; // class Base class Vehicle : virtual public Base { public: Vehicle() : Base() { } ~Vehicle() { } }; // class Vehicle class Car : public Vehicle { public: Car() : Base(), Vehicle() { } ~Car() { } }; // class Car int main(int a_Data, char** argv) { Car* stupid = new Car(); return 0; } Seems easy enough, right? Here's how I compile it, which is the same way I compile the rest of my code: /home/oem/android-ndk-r3/build/prebuilt/linux-x86/arm-eabi-4.4.0/bin/arm-eabi-g++ -g -std=c99 -Wall -Werror -O2 -w -shared -fshort-enums -I ../../YoghurtGum/src/GLES -I ../../YoghurtGum/src -I /home/oem/android-ndk-r3/build/platforms/android-5/arch-arm/usr/include -c src/Inheritance.cpp -o intermediate/Inheritance.o (Line breaks are added for clarity). This compiles fine. But then we get to the linker: /home/oem/android-ndk-r3/build/prebuilt/linux-x86/arm-eabi-4.4.0/bin/arm-eabi-gcc -lstdc++ -Wl, --entry=main, -rpath-link=/system/lib, -rpath-link=/home/oem/android-ndk-r3/build/platforms/android-5/arch-arm/usr/lib, -dynamic-linker=/system/bin/linker, -L/home/oem/android-ndk-r3/build/prebuilt/linux-x86/arm-eabi-4.4.0/lib/gcc/arm-eabi/4.4.0, -L/home/oem/android-ndk-r3/build/platforms/android-5/arch-arm/usr/lib, -rpath=../../YoghurtGum/lib/GLES -nostdlib -lm -lc -lGLESv1_CM -z /home/oem/android-ndk-r3/build/platforms/android-5/arch-arm/usr/lib/crtbegin_dynamic.o /home/oem/android-ndk-r3/build/platforms/android-5/arch-arm/usr/lib/crtend_android.o intermediate/Inheritance.o ../../YoghurtGum/bin/YoghurtGum.a -o bin/Galaxians.android As you can probably tell, there's a lot of cruft in there that isn't really needed. That's because it doesn't work. It fails with the following errors: intermediate/Inheritance.o:(.rodata._ZTI3Car[typeinfo for Car]+0x0): undefined reference to `vtable for __cxxabiv1::__si_class_type_info' intermediate/Inheritance.o:(.rodata._ZTI7Vehicle[typeinfo for Vehicle]+0x0): undefined reference to `vtable for __cxxabiv1::__vmi_class_type_info' intermediate/Inheritance.o:(.rodata._ZTI4Base[typeinfo for Base]+0x0): undefined reference to `vtable for __cxxabiv1::__class_type_info' collect2: ld returned 1 exit status make: *** [bin/Galaxians.android] Fout 1 These are the same errors I get from my actual application. If someone could explain to me where I went wrong in my test or what option or I forgot in my linker, I would be very, extremely grateful. Thanks in advance. UPDATE: When I make my destructors non-inlined, I get new and more exciting link errors: intermediate/Inheritance.o:(.rodata+0x78): undefined reference to `vtable for __cxxabiv1::__si_class_type_info' intermediate/Inheritance.o:(.rodata+0x90): undefined reference to `vtable for __cxxabiv1::__vmi_class_type_info' intermediate/Inheritance.o:(.rodata+0xb0): undefined reference to `vtable for __cxxabiv1::__class_type_info' collect2: ld returned 1 exit status make: *** [bin/Galaxians.android] Fout 1

    Read the article

  • What is a good platform for building a game framework targetting both web and native languages?

    - by fuzzyTew
    I would like to develop (or find, if one is already in development) a framework with support for accelerated graphics and sound built on a system flexible enough to compile to the following: native ppc/x86/x86_64/arm binaries or a language which compiles to them javascript actionscript bytecode or a language which compiles to it (actionscript 3, haxe) optionally java I imagine, for example, creating an API where I can open windows and make OpenGL-like calls and the framework maps this in a relatively efficient manner to either WebGL with a canvas object, 3d graphics in Flash, OpenGL ES 2 with EGL, or desktop OpenGL in an X11, Windows, or Cocoa window. I have so far looked into these avenues: Building the game library in haXe Pros: Targets exist for php, javascript, actionscript bytecode, c++ High level, object oriented language Cons: No support for finally{} blocks or destructors, making resource cleanup difficult C++ target does not allow room for producing highly optimized libraries -- the foreign function interface requires all primitive types be boxed in a wrapper object, as if writing bindings for a scripting language; these feel unideal for real-time graphics and audio, especially exporting low-level functions. Doesn't seem quite yet mature Using the C preprocessor to create a translator, writing programs entirely with macros Pros: CPP is widespread and simple to use Cons: This is an arduous task and probably the wrong tool for the job CPP implementations differ widely in support for features (e.g. xcode cpp has no variadic macros despite claiming C99 compliance) There is little-to-no room for optimization in this route Using llvm's support for multiple backends to target c/c++ to web languages Pros: Can code in c/c++ LLVM is a very mature highly optimizing compiler performing e.g. global inlining Targets exist for actionscript (alchemy) and javascript (emscripten) Cons: Actionscript target is closed source, unmaintained, and buggy. Javascript targets do not use features of HTML5 for appropriate optimization (e.g. linear memory with typed arrays) and are immature An LLVM target must convert from low-level bytecode, so high-level constructs are lost and bloated unreadable code is created from translating individual instructions, which may be more difficult for an unprepared JIT to optimize. "jump" instructions cause problems for languages with no "goto" statements. Using libclang to write a translator from C/C++ to web languages Pros: A beautiful parsing library providing easy access to the code structure Can code in C/C++ Has sponsored developer effort from Apple Cons: Incomplete; current feature set targets IDEs. Basic operators are unexposed and must be manually parsed from the returned AST element to be identified. Translating code prior to compilation may forgo optimizations assumed in c/c++ such as inlining. Creating new code generators for clang to translate into web languages Pros: Can code in C/C++ as libclang Cons: There is no API; code structure is unstable A much larger job than using libclang; the innards of clang are complex Building the game library in Common Lisp Pros: Flexible, ancient, well-developed language Extensive introspection should ease writing translators Translators exist for at least javascript Cons: Unfamiliar language No standardized library functions, widely varying implementations Which of these avenues should I pursue? Do you know of any others, or any systems that might be useful? Does a general project like this exist somewhere already? Thank you for any input.

    Read the article

  • "Use of uninitialised value" despite of memset

    - by Framester
    Hi there, I allocate a 2d array and use memset to fill it with zeros. #include<stdio.h> #include<string.h> #include<stdlib.h> void main() { int m=10; int n =10; int **array_2d; array_2d = (int**) malloc(m*sizeof(int*)); if(array_2d==NULL) { printf("\n Could not malloc 2d array \n"); exit(1); } for(int i=0;i<m;i++) { ((array_2d)[i])=malloc(n*sizeof(int)); memset(((array_2d)[i]),0,sizeof(n*sizeof(int))); } for(int i=0; i<10;i++){ for(int j=0; j<10;j++){ printf("(%i,%i)=",i,j); fflush(stdout); printf("%i ", array_2d[i][j]); } printf("\n"); } } Afterwards I use valgrind [1] to check for memory errors. I get following error: Conditional jump or move depends on uninitialised value(s) for line 24 (printf("%i ", array_2d[i][j]);). I always thought memset is the function to initialize arrays. How can I get rid off this error? Thanks! Valgrind output: ==3485== Memcheck, a memory error detector ==3485== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al. ==3485== Using Valgrind-3.5.0-Debian and LibVEX; rerun with -h for copyright info ==3485== Command: ./a.out ==3485== (0,0)=0 (0,1)===3485== Use of uninitialised value of size 4 ==3485== at 0x409E186: _itoa_word (_itoa.c:195) ==3485== by 0x40A1AD1: vfprintf (vfprintf.c:1613) ==3485== by 0x40A8FFF: printf (printf.c:35) ==3485== by 0x8048724: main (playing_with_valgrind.c:39) ==3485== ==3485== ==3485== ---- Attach to debugger ? --- [Return/N/n/Y/y/C/c] ---- ==3485== Conditional jump or move depends on uninitialised value(s) ==3485== at 0x409E18E: _itoa_word (_itoa.c:195) ==3485== by 0x40A1AD1: vfprintf (vfprintf.c:1613) ==3485== by 0x40A8FFF: printf (printf.c:35) ==3485== by 0x8048724: main (playing_with_valgrind.c:39) [1] valgrind --tool=memcheck --leak-check=yes --show-reachable=yes --num-callers=20 --track-fds=yes --db-attach=yes ./a.out [gcc-cmd] gcc -std=c99 -lm -Wall -g3 playing_with_valgrind.c

    Read the article

  • How to ensure structures are completly initialized (by name) in GCC?

    - by Steven Spark
    How do I ensure each and every field of my structures are initialized in GCC when using designated initializers? (I'm especially interested in function pointers.) (I'm using C not C++.) Here is an example: typedef struct { int a; int b; } foo_t; typedef struct { void (*Start)(void); void (*Stop)(void); } bar_t; foo_t fooo = { 5 }; foo_t food = { .b=4 }; bar_t baro = { NULL }; bar_t bard = { .Start = NULL }; -Wmissing-field-initializers does not help at all. It works for fooo only in GCC (mingw 4.7.3, 4.8.1), and clang does only marginally better (no warnings for food and bard). I'm sure there is a reason for not producing warnings for designated initializer (even when I explicitly ask for them) but I want/need them. I do not want to initialize structures based on order/position because that is more error prone (for example swapping Start and Stop won't even give any warning). And neither gcc nor clang will give any warning that I failed to explicitly initialize a field (when initializing by name). I also don't want to litter my code with if(x.y==NULL) lines for multiple reasons, one of which is I want compile time warnings and not runtime errors. At least splint will give me warnings on all 4 cases, but unfortunately I cannot use splint all the time (it chokes on some of the code (fails to parse some C99, GCC extensions)). Note: If I'm using a real function instead of NULL GCC will also show a warning for baro (but not bard). I searched google and stack overflow but only found related questions and have not found answer for this specific problem. The best match I have found is 'Ensure that all elements in a structure are initialized' Ensure that all elements in a structure are initialized Which asks pretty much the same question, but has no satisfying answer. Is there a better way dealing with this that I have not mentioned? (Maybe other code analysis tool? Preferably something (free) that can be integrated into Eclipse or Visual Studio...)

    Read the article

  • C: copying some structs causes strange behavior

    - by Jenny B
    I have an annoying bug in the line rq->tickets[rq->usedContracts] = toAdd; if i do: rq->tickets[0] = toAdd the program crashes if i do rq->tickets[1] = toAdd; it works valgrind says ==19501== Use of uninitialised value of size 8 and ==19501== Invalid write of size 8 for this very line. What is wrong? struct TS_element { int travels; int originalTravels; int cost; char** dates; int moneyLeft; } TicketSet; struct RQ_element { int usedContracts; struct TS_element* tickets; } RabQav; TicketSetStatus tsCreate(TicketSet* t, int n, int c) { if (n <= 0) return TS_ILLEGAL_PARAMETER; TicketSet* myTicketSet = (TicketSet*) malloc(sizeof(TicketSet)); if (myTicketSet == NULL) { return TS_CANNOT_CREATE; } myTicketSet->usedTravels = 0; myTicketSet->originalTravels = n; myTicketSet->cost = c; myTicketSet->moneyLeft = n * c; char** dates = malloc(sizeof(char**)* (n)); //todo maybe c99 allows dynamic arrays? for (int i = 0; i < n; i++) { dates[i] = malloc(sizeof(char)*GOOD_LENGTH+1); if (dates[i] == NULL) { free(dates); free(t); return TS_CANNOT_CREATE; } } myTicketSet->dates = dates; *t = *myTicketSet; return TS_SUCCESS; } static void copyTicketSets(TicketSet* dest, const TicketSet* source) { dest->usedTravels = source->usedTravels; dest->originalTravels = source->originalTravels; dest->cost = source->cost; dest->moneyLeft = source->moneyLeft; for (int i = 0; i < source->originalTravels; i++) { if (NULL != source->dates[i]) { free(dest->dates[i]); dest->dates[i] = malloc(sizeof(char) * GOOD_LENGTH + 1); if (dest->dates[i] == NULL) { free(dest->dates); //todo free dates 0...i-1 free(dest); return; } strcpy(dest->dates[i], source->dates[i]); } } } RabQavStatus rqLoadTS(RabQav* rq, TicketSet t, DateTime dt) { TicketSet toAdd; TicketSetStatus res = tsCreate(&toAdd, t.originalTravels, t.cost); if (res != TS_SUCCESS) { return RQ_FAIL; } copyTicketSets(&toAdd, &t); rq->tickets[rq->usedContracts] = toAdd; rq->usedContracts++; return RQ_SUCCESS; }

    Read the article

  • Installing nGinX Reverse Proxy on CentOS 5

    - by heavymark
    I'm trying to install nGinX as a reverse proxy on CentOS 5 with apache. The instructions to do this are here: http://wiki.mediatemple.net/w/(dv):Configure_nginx_as_reverse_proxy_web_server Note- in the instructions, for the url to get nginx I'm using the following: http://nginx.org/download/nginx-1.0.10.tar.gz Now here is my problem. After installing the required packages and running .configure I get the following: checking for OS + Linux 2.6.18-028stab094.3 x86_64 checking for C compiler ... found + using GNU C compiler + gcc version: 4.1.2 20080704 (Red Hat 4.1.2-51) checking for gcc -pipe switch ... found checking for gcc builtin atomic operations ... found checking for C99 variadic macros ... found checking for gcc variadic macros ... found checking for unistd.h ... found checking for inttypes.h ... found checking for limits.h ... found checking for sys/filio.h ... not found checking for sys/param.h ... found checking for sys/mount.h ... found checking for sys/statvfs.h ... found checking for crypt.h ... found checking for Linux specific features checking for epoll ... found checking for sendfile() ... found checking for sendfile64() ... found checking for sys/prctl.h ... found checking for prctl(PR_SET_DUMPABLE) ... found checking for sched_setaffinity() ... found checking for crypt_r() ... found checking for sys/vfs.h ... found checking for nobody group ... found checking for poll() ... found checking for /dev/poll ... not found checking for kqueue ... not found checking for crypt() ... not found checking for crypt() in libcrypt ... found checking for F_READAHEAD ... not found checking for posix_fadvise() ... found checking for O_DIRECT ... found checking for F_NOCACHE ... not found checking for directio() ... not found checking for statfs() ... found checking for statvfs() ... found checking for dlopen() ... not found checking for dlopen() in libdl ... found checking for sched_yield() ... found checking for SO_SETFIB ... not found checking for SO_ACCEPTFILTER ... not found checking for TCP_DEFER_ACCEPT ... found checking for accept4() ... not found checking for int size ... 4 bytes checking for long size ... 8 bytes checking for long long size ... 8 bytes checking for void * size ... 8 bytes checking for uint64_t ... found checking for sig_atomic_t ... found checking for sig_atomic_t size ... 4 bytes checking for socklen_t ... found checking for in_addr_t ... found checking for in_port_t ... found checking for rlim_t ... found checking for uintptr_t ... uintptr_t found checking for system endianess ... little endianess checking for size_t size ... 8 bytes checking for off_t size ... 8 bytes checking for time_t size ... 8 bytes checking for setproctitle() ... not found checking for pread() ... found checking for pwrite() ... found checking for sys_nerr ... found checking for localtime_r() ... found checking for posix_memalign() ... found checking for memalign() ... found checking for mmap(MAP_ANON|MAP_SHARED) ... found checking for mmap("/dev/zero", MAP_SHARED) ... found checking for System V shared memory ... found checking for POSIX semaphores ... not found checking for POSIX semaphores in libpthread ... found checking for struct msghdr.msg_control ... found checking for ioctl(FIONBIO) ... found checking for struct tm.tm_gmtoff ... found checking for struct dirent.d_namlen ... not found checking for struct dirent.d_type ... found checking for PCRE library ... found checking for system md library ... not found checking for system md5 library ... not found checking for OpenSSL md5 crypto library ... found checking for sha1 in system md library ... not found checking for OpenSSL sha1 crypto library ... found checking for zlib library ... found creating objs/Makefile Configuration summary + using system PCRE library + OpenSSL library is not used + md5: using system crypto library + sha1: using system crypto library + using system zlib library nginx path prefix: "/usr/local/nginx" nginx binary file: "/usr/local/nginx/sbin/nginx" nginx configuration prefix: "/usr/local/nginx/conf" nginx configuration file: "/usr/local/nginx/conf/nginx.conf" nginx pid file: "/usr/local/nginx/logs/nginx.pid" nginx error log file: "/usr/local/nginx/logs/error.log" nginx http access log file: "/usr/local/nginx/logs/access.log" nginx http client request body temporary files: "client_body_temp" nginx http proxy temporary files: "proxy_temp" nginx http fastcgi temporary files: "fastcgi_temp" nginx http uwsgi temporary files: "uwsgi_temp" nginx http scgi temporary files: "scgi_temp" It says if you get errors to stop and make sure packages are installed. I didn't get errors but as you can see I got several "not founds". Are those considered errors? If so how do I resolve that. And as noted in the link, I cannot install through yum, because it wont work with plesk then. Thanks!

    Read the article

  • Package libxul not fount - Kiwix Wikpedia in Ubuntu Precise 12.04

    - by JHOSmAN
    I'm trying to install the service Kiwix but I need a library that is not available for Ubuntu 12.04 LTS Precise leave the log and if someone could tell me how to install Seller would appreciate. kiwix-0.9# ls aclocal.m4 COMPILE config.sub COPYING install-sh ltmain.sh missing static AUTHORS config.guess configure depcomp kiwix Makefile.am README CHANGELOG config.log configure.ac desktop libxul-dev_1.8.1.16+nobinonly-0ubuntu1_all.deb Makefile.in src root@ubuntu-MM061:/home/ubuntu/Escritorio/kiwix-0.9# ./configure checking for a BSD-compatible install... /usr/bin/install -c checking whether build environment is sane... yes checking for a thread-safe mkdir -p... /bin/mkdir -p checking for gawk... no checking for mawk... mawk checking whether make sets $(MAKE)... yes checking whether to enable maintainer-specific portions of Makefiles... no checking for gcc... gcc checking whether the C compiler works... yes checking for C compiler default output file name... a.out checking for suffix of executables... checking whether we are cross compiling... no checking for suffix of object files... o checking whether we are using the GNU C compiler... yes checking whether gcc accepts -g... yes checking for gcc option to accept ISO C89... none needed checking for style of include used by make... GNU checking dependency style of gcc... gcc3 checking for g++... g++ checking whether we are using the GNU C++ compiler... yes checking whether g++ accepts -g... yes checking dependency style of g++... gcc3 checking for g++... g++ checking for cl... no checking for cl... no checking for Xcode... no checking for jar... jar checking build system type... i686-pc-linux-gnu checking host system type... i686-pc-linux-gnu checking for a sed that does not truncate output... /bin/sed checking for grep that handles long lines and -e... /bin/grep checking for egrep... /bin/grep -E checking for fgrep... /bin/grep -F checking for ld used by gcc... /usr/bin/ld checking if the linker (/usr/bin/ld) is GNU ld... yes checking for BSD- or MS-compatible name lister (nm)... /usr/bin/nm -B checking the name lister (/usr/bin/nm -B) interface... BSD nm checking whether ln -s works... yes checking the maximum length of command line arguments... 1572864 checking whether the shell understands some XSI constructs... yes checking whether the shell understands "+="... yes checking for /usr/bin/ld option to reload object files... -r checking for objdump... objdump checking how to recognize dependent libraries... pass_all checking for ar... ar checking for strip... strip checking for ranlib... ranlib checking command to parse /usr/bin/nm -B output from gcc object... ok checking how to run the C preprocessor... gcc -E checking for ANSI C header files... yes checking for sys/types.h... yes checking for sys/stat.h... yes checking for stdlib.h... yes checking for string.h... yes checking for memory.h... yes checking for strings.h... yes checking for inttypes.h... yes checking for stdint.h... yes checking for unistd.h... yes checking for dlfcn.h... yes checking whether we are using the GNU C++ compiler... (cached) yes checking whether g++ accepts -g... (cached) yes checking dependency style of g++... (cached) gcc3 checking how to run the C++ preprocessor... g++ -E checking for objdir... .libs checking if gcc supports -fno-rtti -fno-exceptions... no checking for gcc option to produce PIC... -fPIC -DPIC checking if gcc PIC flag -fPIC -DPIC works... yes checking if gcc static flag -static works... yes checking if gcc supports -c -o file.o... yes checking if gcc supports -c -o file.o... (cached) yes checking whether the gcc linker (/usr/bin/ld) supports shared libraries... yes checking whether -lc should be explicitly linked in... no checking dynamic linker characteristics... GNU/Linux ld.so checking how to hardcode library paths into programs... immediate checking whether stripping libraries is possible... yes checking if libtool supports shared libraries... yes checking whether to build shared libraries... yes checking whether to build static libraries... yes checking for ld used by g++... /usr/bin/ld checking if the linker (/usr/bin/ld) is GNU ld... yes checking whether the g++ linker (/usr/bin/ld) supports shared libraries... yes checking for g++ option to produce PIC... -fPIC -DPIC checking if g++ PIC flag -fPIC -DPIC works... yes checking if g++ static flag -static works... yes checking if g++ supports -c -o file.o... yes checking if g++ supports -c -o file.o... (cached) yes checking whether the g++ linker (/usr/bin/ld) supports shared libraries... yes checking dynamic linker characteristics... GNU/Linux ld.so checking how to hardcode library paths into programs... immediate checking for ranlib... (cached) ranlib checking whether make sets $(MAKE)... (cached) yes checking for pkg-config... pkg-config checking for perl... perl checking fcntl.h usability... yes checking fcntl.h presence... yes checking for fcntl.h... yes checking float.h usability... yes checking float.h presence... yes checking for float.h... yes checking libintl.h usability... yes checking libintl.h presence... yes checking for libintl.h... yes checking limits.h usability... yes checking limits.h presence... yes checking for limits.h... yes checking stddef.h usability... yes checking stddef.h presence... yes checking for stddef.h... yes checking for stdint.h... (cached) yes checking for stdlib.h... (cached) yes checking for string.h... (cached) yes checking for strings.h... (cached) yes checking sys/socket.h usability... yes checking sys/socket.h presence... yes checking for sys/socket.h... yes checking sys/time.h usability... yes checking sys/time.h presence... yes checking for sys/time.h... yes checking for unistd.h... (cached) yes checking wchar.h usability... yes checking wchar.h presence... yes checking for wchar.h... yes checking for stdbool.h that conforms to C99... yes checking for _Bool... no checking for inline... inline checking for int16_t... yes checking for int32_t... yes checking for int64_t... yes checking for int8_t... yes checking for off_t... yes checking for pid_t... yes checking for size_t... yes checking for uint16_t... yes checking for uint32_t... yes checking for uint64_t... yes checking for uint8_t... yes checking for ptrdiff_t... yes checking vfork.h usability... no checking vfork.h presence... no checking for vfork.h... no checking for fork... yes checking for vfork... yes checking for working fork... yes checking for working vfork... (cached) yes checking for stdlib.h... (cached) yes checking for GNU libc compatible malloc... yes checking for working strtod... yes checking for getcwd... yes checking for gettimeofday... yes checking for memmove... yes checking for memset... yes checking for pow... yes checking for regcomp... yes checking for sqrt... yes checking for strcasecmp... yes checking for strchr... yes checking for strdup... yes checking for strerror... yes checking for strtol... yes Package libxul was not found in the pkg-config search path. Perhaps you should add the directory containing libxul.pc' to the PKG_CONFIG_PATH environment variable No package 'libxul' found Package libxul was not found in the pkg-config search path. Perhaps you should add the directory containinglibxul.pc' to the PKG_CONFIG_PATH environment variable No package 'libxul' found checking for /stable... no checking for "/nsISupports.idl"... no configure: error: unable to find nsISupports.idl apt-get install libxul Leyendo lista de paquetes... Hecho Creando árbol de dependencias Leyendo la información de estado... Hecho E: No se ha podido localizar el paquete libxul

    Read the article

  • css sticky footer without scrolbar

    - by massinissa
    How to do to avoid having the scroller with a sticky footer to the bottom of the page (not bottom of window)? When I remove height=100% from content and sidebar, I'm no more getting the scroller. However, when doing so, my content and sidebar do not fill all the space down to the footer. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <title>Untitled 13</title> <style media="all" type="text/css"> * { margin: 0; padding: 0; } html, body, #wrap, form { height: 100%; } #wrap, #footer { width: 750px; margin: 0 auto; } #wrap { background: #cff; } html, body { color: #000; background: #a7a09a; } body > #wrap { height: 100%; min-height: 100%; } form { /*height: auto;*/ min-height: 100%; } #main { background: #000; height:100%; min-height:100%; height: auto !important; */ } #content { height:100%; float: left; padding: 10px; float: left; width: 570px; background: #9c9; } #sidebar { height:100%; float: left; width: 140px; background: #c99; padding: 10px; } #footer { position: relative; margin-top: -100px; height: 100px; clear: both; background: #cc9; bottom: 0; } .clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; } .clearfix { display: inline-block; } * html .clearfix { height: 1%; } .clearfix { display: block; } #header { /*padding: 5px 10px;*/ background: #ddd; } </style> </head> <body> <form id="form1" runat="server"> <div id="wrap"> <div id="main" class="clearfix"> <div id="header"> <h1>header</h1> </div> <div id="sidebar"> <h2>sidebar</h2> </div> <div id="content"> <h2>main content</h2> </div> </div> </div> <div id="footer"> <h2>footer</h2> </div> </form> </body> </html>

    Read the article

  • ERROR: Failed to build gem native extension on Mavericks

    - by Kyle Decot
    I'm attempting to run bundle in my Rails project on OSX 10.9. It fails when getting to the pg gem with this error: Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension. /Users/kyledecot/.rvm/rubies/ruby-2.0.0-p247/bin/ruby extconf.rb checking for pg_config... no No pg_config... trying anyway. If building fails, please try again with --with-pg-config=/path/to/pg_config checking for libpq-fe.h... yes checking for libpq/libpq-fs.h... yes checking for pg_config_manual.h... yes checking for PQconnectdb() in -lpq... yes checking for PQconnectionUsedPassword()... yes checking for PQisthreadsafe()... yes checking for PQprepare()... yes checking for PQexecParams()... yes checking for PQescapeString()... yes checking for PQescapeStringConn()... yes checking for PQescapeLiteral()... yes checking for PQescapeIdentifier()... yes checking for PQgetCancel()... yes checking for lo_create()... yes checking for pg_encoding_to_char()... yes checking for pg_char_to_encoding()... yes checking for PQsetClientEncoding()... yes checking for PQlibVersion()... yes checking for PQping()... yes checking for PQsetSingleRowMode()... yes checking for rb_encdb_alias()... yes checking for rb_enc_alias()... no checking for rb_thread_call_without_gvl()... yes checking for rb_thread_call_with_gvl()... yes checking for rb_thread_fd_select()... yes checking for rb_w32_wrap_io_handle()... no checking for PGRES_COPY_BOTH in libpq-fe.h... no checking for PGRES_SINGLE_TUPLE in libpq-fe.h... no checking for PG_DIAG_TABLE_NAME in libpq-fe.h... no checking for struct pgNotify.extra in libpq-fe.h... yes checking for unistd.h... yes checking for ruby/st.h... yes creating extconf.h creating Makefile make "DESTDIR=" compiling gvl_wrappers.c clang: warning: argument unused during compilation: '-fno-fast-math' compiling pg.c clang: warning: argument unused during compilation: '-fno-fast-math' pg.c:272:9: warning: implicit declaration of function 'PQlibVersion' is invalid in C99 [-Wimplicit-function-declaration] return INT2NUM(PQlibVersion()); ^ In file included from pg.c:48: In file included from ./pg.h:17: In file included from /Users/kyledecot/.rvm/rubies/ruby-2.0.0-p247/include/ruby-2.0.0/ruby.h:33: /Users/kyledecot/.rvm/rubies/ruby-2.0.0-p247/include/ruby-2.0.0/ruby/ruby.h:1167:21: note: instantiated from: # define INT2NUM(v) INT2FIX((int)(v)) ^ pg.c:272:9: note: instantiated from: return INT2NUM(PQlibVersion()); ^ pg.c:272:17: note: instantiated from: return INT2NUM(PQlibVersion()); ^ pg.c:375:48: error: use of undeclared identifier 'PQPING_OK' rb_define_const(rb_mPGconstants, "PQPING_OK", INT2FIX(PQPING_OK)); ^ pg.c:375:56: note: instantiated from: rb_define_const(rb_mPGconstants, "PQPING_OK", INT2FIX(PQPING_OK)); ^ pg.c:377:52: error: use of undeclared identifier 'PQPING_REJECT' rb_define_const(rb_mPGconstants, "PQPING_REJECT", INT2FIX(PQPING_REJECT)); ^ pg.c:377:60: note: instantiated from: rb_define_const(rb_mPGconstants, "PQPING_REJECT", INT2FIX(PQPING_REJECT)); ^ pg.c:379:57: error: use of undeclared identifier 'PQPING_NO_RESPONSE' rb_define_const(rb_mPGconstants, "PQPING_NO_RESPONSE", INT2FIX(PQPING_NO_RESPONSE)); ^ pg.c:379:65: note: instantiated from: rb_define_const(rb_mPGconstants, "PQPING_NO_RESPONSE", INT2FIX(PQPING_NO_RESPONSE)); ^ pg.c:381:56: error: use of undeclared identifier 'PQPING_NO_ATTEMPT' rb_define_const(rb_mPGconstants, "PQPING_NO_ATTEMPT", INT2FIX(PQPING_NO_ATTEMPT)); ^ pg.c:381:64: note: instantiated from: rb_define_const(rb_mPGconstants, "PQPING_NO_ATTEMPT", INT2FIX(PQPING_NO_ATTEMPT)); ^ 1 warning and 4 errors generated. make: *** [pg.o] Error 1 Gem files will remain installed in /Users/kyledecot/.rvm/gems/ruby-2.0.0-p247@skateboxes/gems/pg-0.17.0 for inspection. Results logged to /Users/kyledecot/.rvm/gems/ruby-2.0.0-p247@skateboxes/gems/pg-0.17.0/ext/gem_make.out An error occurred while installing pg (0.17.0), and Bundler cannot continue. Make sure that `gem install pg -v '0.17.0'` succeeds before bundling.

    Read the article

  • how to solve unhandled exception error when using visual C++ 2008?

    - by make
    Hi, Could someone please help me to solve unhandled exception error when using visual C++ 2008? the error is displayed as follow: Unhandled exception at 0x00411690 in time.exe: 0xC0000005: Access violation reading location 0x00000008 Actually when I used visual c++ 6 in the past, there weren't any error and the program was running fine. But now ehen I use visual 2008, I am getting this Unhandled exception error. Here is the program: #include <stdio.h> #include <stdlib.h> #include <time.h> #ifdef _WIN32 // #include <winsock.h> #include <windows.h> #include "stdint.h" // typedef __int64 int64_t // Define it from MSVC's internal type // typedef unsigned __int32 uint32_t #else #include <stdint.h> // Use the C99 official header #include <sys/time.h> #include <unistd.h> #endif #if defined(_MSC_VER) || defined(_MSC_EXTENSIONS) #define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64 #else #define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL #endif struct timezone { int tz_minuteswest; /* minutes W of Greenwich */ int tz_dsttime; /* type of dst correction */ }; #define TEST #ifdef TEST uint32_t stampstart(); uint32_t stampstop(uint32_t start); int main() { uint32_t start, stop; start = stampstart(); /* Your code goes here */ stop = stampstop(start); return 0; } #endif int gettimeofday(struct timeval *tv, struct timezone *tz) { FILETIME ft; unsigned __int64 tmpres = 0; static int tzflag = 0; if (NULL != tv) { GetSystemTimeAsFileTime(&ft); tmpres |= ft.dwHighDateTime; tmpres <<= 32; tmpres |= ft.dwLowDateTime; tmpres /= 10; /*convert into microseconds*/ /*converting file time to unix epoch*/ tmpres -= DELTA_EPOCH_IN_MICROSECS; tv->tv_sec = (long)(tmpres / 1000000UL); tv->tv_usec = (long)(tmpres % 1000000UL); } if (NULL != tz) { if (!tzflag) { _tzset(); tzflag++; } tz->tz_minuteswest = _timezone / 60; tz->tz_dsttime = _daylight; } return 0; } uint32_t stampstart() { struct timeval tv; struct timezone tz; struct tm *tm; uint32_t start; gettimeofday(&tv, &tz); tm = localtime(&tv.tv_sec); printf("TIMESTAMP-START\t %d:%02d:%02d:%d (~%d ms)\n", tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec, tm->tm_hour * 3600 * 1000 + tm->tm_min * 60 * 1000 + tm->tm_sec * 1000 + tv.tv_usec / 1000); start = tm->tm_hour * 3600 * 1000 + tm->tm_min * 60 * 1000 + tm->tm_sec * 1000 + tv.tv_usec / 1000; return (start); } uint32_t stampstop(uint32_t start) { struct timeval tv; struct timezone tz; struct tm *tm; uint32_t stop; gettimeofday(&tv, &tz); tm = localtime(&tv.tv_sec); stop = tm->tm_hour * 3600 * 1000 + tm->tm_min * 60 * 1000 + tm->tm_sec * 1000 + tv.tv_usec / 1000; printf("TIMESTAMP-END\t %d:%02d:%02d:%d (~%d ms) \n", tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec, tm->tm_hour * 3600 * 1000 + tm->tm_min * 60 * 1000 + tm->tm_sec * 1000 + tv.tv_usec / 1000); printf("ELAPSED\t %d ms\n", stop - start); return (stop); } thanks for your replies:

    Read the article

  • numpy calling sse2 via ctypes

    - by Daniel
    Hello, In brief, I am trying to call into a shared library from python, more specifically, from numpy. The shared library is implemented in C using sse2 instructions. Enabling optimisation, i.e. building the library with -O2 or –O1, I am facing strange segfaults when calling into the shared library via ctypes. Disabling optimisation (-O0), everything works out as expected, as is the case when linking the library to a c-program directly (optimised or not). Attached you find a snipped which exhibits the delineated behaviour on my system. With optimisation enabled, gdb reports a segfault in __builtin_ia32_loadupd (__P) at emmintrin.h:113. The value of __P is reported as optimised out. test.c: #include <emmintrin.h> #include <complex.h> void test(const int m, const double* x, double complex* y) { int i; __m128d _f, _x, _b; double complex f __attribute__( (aligned(16)) ); double complex b __attribute__( (aligned(16)) ); __m128d* _p; b = 1; _b = _mm_loadu_pd( (double *) &b ); _p = (__m128d*) y; for(i=0; i<m; ++i) { f = cexp(-I*x[i]); _f = _mm_loadu_pd( (double *) &f ); _x = _mm_loadu_pd( (double *) &x[i] ); _f = _mm_shuffle_pd(_f, _f, 1); *_p = _mm_add_pd(*_p, _f); *_p = _mm_add_pd(*_p, _x); *_p = _mm_mul_pd(*_p,_b); _p++; } return; } Compiler flags: gcc -o libtest.so -shared -std=c99 -msse2 -fPIC -O2 -g -lm test.c test.py: import numpy as np import os def zerovec_aligned(nr, dtype=np.float64, boundary=16): '''Create an aligned array of zeros. ''' size = nr * np.dtype(dtype).itemsize tmp = np.zeros(size + boundary, dtype=np.uint8) address = tmp.__array_interface__['data'][0] offset = boundary - address % boundary return tmp[offset:offset + size].view(dtype=dtype) lib = np.ctypeslib.load_library('libtest', '.' ) lib.test.restype = None lib.test.argtypes = [np.ctypeslib.ctypes.c_int, np.ctypeslib.ndpointer(np.float64, flags=('C', 'A') ), np.ctypeslib.ndpointer(np.complex128, flags=('C', 'A', 'W') )] n = 13 y = zerovec_aligned(n, dtype=np.complex128) x = np.ones(n, dtype=np.float64) # x = zerovec_aligned(n, dtype=np.float64) # x[:] = 1. lib.test(n,x,y) My system: Ubuntu Linux i686 2.6.31-22-generic Compiler: gcc (Ubuntu 4.4.1-4ubuntu9) Python: Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1] Numpy: 1.4.0 I have taken provisions (cf. python code) that y is aligned and the alignment of x should not matter (I think; explicitly aligning x does not solve the problem though). Note also that i use _mm_loadu_pd instead of _mm_load_pd when loading b and f. For the C-only version _mm_load_pd works (as expected). However, when calling the function via ctypes using _mm_load_pd always segfaults (independent of optimisation). I have tried several days to sort out this issue without success ... and I am on the verge beating my monitor to death. Any input welcome. Daniel

    Read the article

  • hello-1.mod.c:14: warning: missing initializer (near initialization for '__this_module.arch.unw_sec_init')

    - by Sompom
    I am trying to write a module for an sbc1651. Since the device is ARM, this requires a cross-compile. As a start, I am trying to compile the "Hello Kernel" module found here. This compiles fine on my x86 development system, but when I try to cross-compile I get the below error. /home/developer/HelloKernel/hello-1.mod.c:14: warning: missing initializer /home/developer/HelloKernel/hello-1.mod.c:14: warning: (near initialization for '__this_module.arch.unw_sec_init') Since this is in the .mod.c file, which is autogenerated I have no idea what's going on. The mod.c file seems to be generated by the module.h file. As far as I can tell, the relevant parts are the same between my x86 system's module.h and the arm kernel header's module.h. Adding to my confusion, this problem is either not googleable (by me...) or hasn't happened to anyone before. Or I'm just doing something clueless that anyone with any sense wouldn't do. The cross-compiler I'm using was supplied by Freescale (I think). I suppose it could be a problem with the compiler. Would it be worth trying to build the toolchain myself? Obviously, since this is a warning, I could ignore it, but since it's so strange, I am worried about it, and would like to at least know the cause... Thanks very much, Sompom Here are the source files hello-1.mod.c #include <linux/module.h> #include <linux/vermagic.h> #include <linux/compiler.h> MODULE_INFO(vermagic, VERMAGIC_STRING); struct module __this_module __attribute__((section(".gnu.linkonce.this_module"))) = { .name = KBUILD_MODNAME, .init = init_module, #ifdef CONFIG_MODULE_UNLOAD .exit = cleanup_module, #endif .arch = MODULE_ARCH_INIT, }; static const struct modversion_info ____versions[] __used __attribute__((section("__versions"))) = { { 0x3972220f, "module_layout" }, { 0xefd6cf06, "__aeabi_unwind_cpp_pr0" }, { 0xea147363, "printk" }, }; static const char __module_depends[] __used __attribute__((section(".modinfo"))) = "depends="; hello-1.c (modified slightly from the given link) /* hello-1.c - The simplest kernel module. * * Copyright (C) 2001 by Peter Jay Salzman * * 08/02/2006 - Updated by Rodrigo Rubira Branco <[email protected]> */ /* Kernel Programming */ #ifndef MODULE #define MODULE #endif #ifndef LINUX #define LINUX #endif #ifndef __KERNEL__ #define __KERNEL__ #endif #include <linux/module.h> /* Needed by all modules */ #include <linux/kernel.h> /* Needed for KERN_ALERT */ static int hello_init_module(void) { printk(KERN_ALERT "Hello world 1.\n"); /* A non 0 return means init_module failed; module can't be loaded.*/ return 0; } static void hello_cleanup_module(void) { printk(KERN_ALERT "Goodbye world 1.\n"); } module_init(hello_init_module); module_exit(hello_cleanup_module); MODULE_LICENSE("GPL"); Makefile export ARCH:=arm export CCPREFIX:=/opt/freescale/usr/local/gcc-4.4.4-glibc-2.11.1-multilib-1.0/arm-fsl-linux-gnueabi/bin/arm-linux- export CROSS_COMPILE:=${CCPREFIX} TARGET := hello-1 WARN := -W -Wall -Wstrict-prototypes -Wmissing-prototypes -Wno-sign-compare -Wno-unused -Werror UNUSED_FLAGS := -std=c99 -pedantic EXTRA_CFLAGS := -O2 -DMODULE -D__KERNEL__ ${WARN} ${INCLUDE} KDIR ?= /home/developer/src/ltib-microsys/ltib/rpm/BUILD/linux-2.6.35.3 ifneq ($(KERNELRELEASE),) # kbuild part of makefile obj-m := $(TARGET).o else # normal makefile default: clean $(MAKE) -C $(KDIR) M=$$PWD .PHONY: clean clean: -rm built-in.o -rm $(TARGET).ko -rm $(TARGET).ko.unsigned -rm $(TARGET).mod.c -rm $(TARGET).mod.o -rm $(TARGET).o -rm modules.order -rm Module.symvers endif

    Read the article

  • Nested loop traversing arrays

    - by alecco
    There are 2 very big series of elements, the second 100 times bigger than the first. For each element of the first series, there are 0 or more elements on the second series. This can be traversed and processed with 2 nested loops. But the unpredictability of the amount of matching elements for each member of the first array makes things very, very slow. The actual processing of the 2nd series of elements involves logical and (&) and a population count. I couldn't find good optimizations using C but I am considering doing inline asm, doing rep* mov* or similar for each element of the first series and then doing the batch processing of the matching bytes of the second series, perhaps in buffers of 1MB or something. But the code would be get quite messy. Does anybody know of a better way? C preferred but x86 ASM OK too. Many thanks! Sample/demo code with simplified problem, first series are "people" and second series are "events", for clarity's sake. (the original problem is actually 100m and 10,000m entries!) #include <stdio.h> #include <stdint.h> #define PEOPLE 1000000 // 1m struct Person { uint8_t age; // Filtering condition uint8_t cnt; // Number of events for this person in E } P[PEOPLE]; // Each has 0 or more bytes with bit flags #define EVENTS 100000000 // 100m uint8_t P1[EVENTS]; // Property 1 flags uint8_t P2[EVENTS]; // Property 2 flags void init_arrays() { for (int i = 0; i < PEOPLE; i++) { // just some stuff P[i].age = i & 0x07; P[i].cnt = i % 220; // assert( sum < EVENTS ); } for (int i = 0; i < EVENTS; i++) { P1[i] = i % 7; // just some stuff P2[i] = i % 9; // just some other stuff } } int main(int argc, char *argv[]) { uint64_t sum = 0, fcur = 0; int age_filter = 7; // just some init_arrays(); // Init P, P1, P2 for (int64_t p = 0; p < PEOPLE ; p++) if (P[p].age < age_filter) for (int64_t e = 0; e < P[p].cnt ; e++, fcur++) sum += __builtin_popcount( P1[fcur] & P2[fcur] ); else fcur += P[p].cnt; // skip this person's events printf("(dummy %ld %ld)\n", sum, fcur ); return 0; } gcc -O5 -march=native -std=c99 test.c -o test

    Read the article

  • SWIG & C/C++ Python API connected - SEGFAULT

    - by user289637
    Hello, my task is to create dual program. At the beginning I start C program that calls throught C/C++ API of Python some Python method. The called method after that call a function that is created with SWIG. I show you my sample also with backtrace from gdb after I am given Segmentation fault. main.c: #include <Python.h> #include <stdio.h> #include "utils.h" int main(int argc, char** argv) { printf("Calling from C !\n"); increment(); int i; for(i = 0; i < 11; ++i) { Py_Initialize(); PyObject *pname = PyString_FromString("py_function"); PyObject *module = PyImport_Import(pname); PyObject *dict = PyModule_GetDict(module); PyObject *func = PyDict_GetItemString(dict, "ink"); PyObject_CallObject(func, NULL); Py_DECREF(module); Py_DECREF(pname); printf("\tbefore finalize\n"); Py_Finalize(); printf("\tafter finalize\n"); } return 0; } utils.c #include <stdio.h> #include "utils.h" void increment(void) { printf("Incremention counter to: %u\n", ++counter); } py_function.py #!/usr/bin/python2.6 '''py_function.py - Python source designed to demonstrate the use of python embedding''' import utils def ink(): print 'I am gonna increment !' utils.increment() and last think is my Makefile & SWIG configure file Makefile: CC=gcc CFLAGS=-c -g -Wall -std=c99 all: main main: main.o utils.o utils_wrap.o $(CC) main.o utils.o -lpython2.6 -o sample swig -Wall -python -o utils_wrap.c utils.i $(CC) utils.o utils_wrap.o -shared -o _utils.so main.o: main.c $(CC) $(CFLAGS) main.c -I/usr/include/python2.6 -o main.o utils.o: utils.c utils.h $(CC) $(CFLAGS) -fPIC utils.c -o $@ utils_wrap.o: utils_wrap.c $(CC) -c -fPIC utils_wrap.c -I/usr/include/python2.6 -o $@ clean: rm -rf *.o The program is called by ./main and there is output: (gdb) run Starting program: /home/marxin/Programming/python2/sample [Thread debugging using libthread_db enabled] Calling from C ! Incremention counter to: 1 I am gonna increment ! Incremention counter to: 2 before finalize after finalize I am gonna increment ! Incremention counter to: 3 before finalize after finalize I am gonna increment ! Incremention counter to: 4 before finalize after finalize Program received signal SIGSEGV, Segmentation fault. 0xb7ed3e4e in PyObject_Malloc () from /usr/lib/libpython2.6.so.1.0 Backtrace: (gdb) backtrace #0 0xb7ed3e4e in PyObject_Malloc () from /usr/lib/libpython2.6.so.1.0 #1 0xb7ca2b2c in ?? () #2 0xb7f8dd40 in ?? () from /usr/lib/libpython2.6.so.1.0 #3 0xb7eb014c in ?? () from /usr/lib/libpython2.6.so.1.0 #4 0xb7f86ff4 in ?? () from /usr/lib/libpython2.6.so.1.0 #5 0xb7f99820 in ?? () from /usr/lib/libpython2.6.so.1.0 #6 0x00000001 in ?? () #7 0xb7f8dd40 in ?? () from /usr/lib/libpython2.6.so.1.0 #8 0xb7f4f014 in _PyObject_GC_Malloc () from /usr/lib/libpython2.6.so.1.0 #9 0xb7f99820 in ?? () from /usr/lib/libpython2.6.so.1.0 #10 0xb7f4f104 in _PyObject_GC_NewVar () from /usr/lib/libpython2.6.so.1.0 #11 0xb7ee8760 in _PyType_Lookup () from /usr/lib/libpython2.6.so.1.0 #12 0xb7f99820 in ?? () from /usr/lib/libpython2.6.so.1.0 #13 0x00000001 in ?? () #14 0xb7f8dd40 in ?? () from /usr/lib/libpython2.6.so.1.0 #15 0xb7ef13ed in ?? () from /usr/lib/libpython2.6.so.1.0 #16 0xb7f86ff4 in ?? () from /usr/lib/libpython2.6.so.1.0 #17 0x00000001 in ?? () #18 0xbfff0c34 in ?? () #19 0xb7e993c3 in ?? () from /usr/lib/libpython2.6.so.1.0 #20 0x00000001 in ?? () #21 0xbfff0c70 in ?? () #22 0xb7f99da0 in ?? () from /usr/lib/libpython2.6.so.1.0 #23 0xb7f86ff4 in ?? () from /usr/lib/libpython2.6.so.1.0 #24 0xb7f86ff4 in ?? () from /usr/lib/libpython2.6.so.1.0 #25 0x080a6b0c in ?? () #26 0x080a6b0c in ?? () #27 0xb7e99420 in PyObject_CallFunctionObjArgs () from /usr/lib/libpython2.6.so.1.0 #28 0xb7f86ff4 in ?? () from /usr/lib/libpython2.6.so.1.0 #29 0xb7f86ff4 in ?? () from /usr/lib/libpython2.6.so.1.0 #30 0x800e55eb in ?? () #31 0x080a6b0c in ?? () #32 0xb7e9958c in PyObject_IsSubclass () from /usr/lib/libpython2.6.so.1.0 #33 0xb7f8dd40 in ?? () from /usr/lib/libpython2.6.so.1.0 #34 0x080a9020 in ?? () #35 0xb7fb78f0 in PyFPE_counter () from /usr/lib/libpython2.6.so.1.0 #36 0xb7f86ff4 in ?? () from /usr/lib/libpython2.6.so.1.0 #37 0x00000000 in ?? () Thanks for your help and advices, marxin

    Read the article

  • How can I get the following compiled on UVA?

    - by Michael Tsang
    Note the comment below. It cannot compiled on UVA because of a bug in GCC. #include <cstdio> #include <cstring> #include <cctype> #include <map> #include <stdexcept> class Board { public: bool read(FILE *); enum Colour {none, white, black}; Colour check() const; private: struct Index { size_t x; size_t y; Index &operator+=(const Index &) throw(std::range_error); Index operator+(const Index &) const throw(std::range_error); }; const static std::size_t size = 8; char data[size][size]; // Cannot be compiled on GCC 4.1.2 due to GCC bug 29993 // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=29993 typedef bool CheckFunction(Colour, const Index &) const; CheckFunction pawn, knight, bishop, king, rook; bool queen(const Colour c, const Index &location) const { return rook(c, location) || bishop(c, location); } static char get_king(Colour c) { return c == white ? 'k' : 'K'; } template<std::size_t n> bool check_consecutive(Colour c, const Index &location, const Index (&offsets)[n]) const { for(const Index *p = offsets; p != (&offsets)[1]; ++p) { try { Index target = location + *p; for(; data[target.x][target.y] == '.'; target += *p) { } if(data[target.x][target.y] == get_king(c)) return true; } catch(std::range_error &) { } } return false; } template<std::size_t n> bool check_distinct(Colour c, const Index &location, const Index (&offsets)[n]) const { for(const Index *p = offsets; p != (&offsets)[1]; ++p) { try { Index target = location + *p; if(data[target.x][target.y] == get_king(c)) return true; } catch(std::range_error &) { } } return false; } }; int main() { Board board; for(int d = 1; board.read(stdin); ++d) { Board::Colour c = board.check(); const char *sp; switch(c) { case Board::black: sp = "white"; break; case Board::white: sp = "black"; break; case Board::none: sp = "no"; break; } std::printf("Game #%d: %s king is in check.\n", d, sp); std::getchar(); // discard empty line } } bool Board::read(FILE *f) { static const char empty[] = "........" "........" "........" "........" "........" "........" "........" "........"; // 64 dots for(char (*p)[size] = data; p != (&data)[1]; ++p) { std::fread(*p, size, 1, f); std::fgetc(f); // discard new-line } return std::memcmp(empty, data, sizeof data); } Board::Colour Board::check() const { std::map<char, CheckFunction Board::*> fp; fp['P'] = &Board::pawn; fp['N'] = &Board::knight; fp['B'] = &Board::bishop; fp['Q'] = &Board::queen; fp['K'] = &Board::king; fp['R'] = &Board::rook; for(std::size_t i = 0; i != size; ++i) { for(std::size_t j = 0; j != size; ++j) { CheckFunction Board::* p = fp[std::toupper(data[i][j])]; if(p) { Colour ret; if(std::isupper(data[i][j])) ret = white; else ret = black; if((this->*p)(ret, (Index){i, j}/* C99 extension */)) return ret; } } } return none; } bool Board::pawn(const Colour c, const Index &location) const { const std::ptrdiff_t sh = c == white ? -1 : 1; const Index offsets[] = { {sh, 1}, {sh, -1} }; return check_distinct(c, location, offsets); } bool Board::knight(const Colour c, const Index &location) const { static const Index offsets[] = { {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2} }; return check_distinct(c, location, offsets); } bool Board::bishop(const Colour c, const Index &location) const { static const Index offsets[] = { {1, 1}, {1, -1}, {-1, -1}, {-1, 1} }; return check_consecutive(c, location, offsets); } bool Board::rook(const Colour c, const Index &location) const { static const Index offsets[] = { {1, 0}, {0, -1}, {0, 1}, {-1, 0} }; return check_consecutive(c, location, offsets); } bool Board::king(const Colour c, const Index &location) const { static const Index offsets[] = { {-1, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1} }; return check_distinct(c, location, offsets); } Board::Index &Board::Index::operator+=(const Index &rhs) throw(std::range_error) { if(x + rhs.x >= size || y + rhs.y >= size) throw std::range_error("result is larger than size"); x += rhs.x; y += rhs.y; return *this; } Board::Index Board::Index::operator+(const Index &rhs) const throw(std::range_error) { Index ret = *this; return ret += rhs; }

    Read the article

  • Inserting Records in Ascending Order function- C homework assignment

    - by Aaron McRuer
    Good day, Stack Overflow. I have a homework assignment that I'm working on this weekend that I'm having a bit of a problem with. We have a struct "Record" (which contains information about cars for a dealership) that gets placed in a particular spot in a linked list according to 1) its make and 2) according to its model year. This is done when initially building the list, when a "int insertRecordInAscendingOrder" function is called in Main. In "insertRecordInAscendingOrder", a third function, "createRecord" is called, where the linked list is created. The function then goes to the function "compareCars" to determine what elements get put where. Depending on the value returned by this function, insertRecordInAscendingOrder then places the record where it belongs. The list is then printed out. There's more to the assignment, but I'll cross that bridge when I come to it. Ideally, and for the assignment to be considered correct, the linked list must be ordered as: Chevrolet 2012 25 Chevrolet 2013 10 Ford 2010 5 Ford 2011 3 Ford 2012 15 Honda 2011 9 Honda 2012 3 Honda 2013 12 Toyota 2009 2 Toyota 2011 7 Toyota 2013 20 from the a text file that has the data ordered the following way: Ford 2012 15 Ford 2011 3 Ford 2010 5 Toyota 2011 7 Toyota 2012 20 Toyota 2009 2 Honda 2011 9 Honda 2012 3 Honda 2013 12 Chevrolet 2013 10 Chevrolet 2012 25 Notice that the alphabetical order of the "make" field takes precedence, then, the model year is arranged from oldest to newest. However, the program produces this as the final list: Chevrolet 2012 25 Chevrolet 2013 10 Honda 2011 9 Honda 2012 3 Honda 2013 12 Toyota 2009 2 Toyota 2011 7 Toyota 2012 20 Ford 2010 5 Ford 2011 3 Ford 2012 15 I sat down with a grad student and tried to work out all of this yesterday, but we just couldn't figure out why it was kicking the Ford nodes down to the end of the list. Here's the code. As you'll notice, I included a printList call at each instance of the insertion of a node. This way, you can see just what is happening when the nodes are being put in "order". It is in ANSI C99. All function calls must be made as they are specified, so unfortunately, there's no real way of getting around this problem by creating a more efficient algorithm. #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_LINE 50 #define MAX_MAKE 20 typedef struct record { char *make; int year; int stock; struct record *next; } Record; int compareCars(Record *car1, Record *car2); void printList(Record *head); Record* createRecord(char *make, int year, int stock); int insertRecordInAscendingOrder(Record **head, char *make, int year, int stock); int main(int argc, char **argv) { FILE *inFile = NULL; char line[MAX_LINE + 1]; char *make, *yearStr, *stockStr; int year, stock, len; Record* headRecord = NULL; /*Input and file diagnostics*/ if (argc!=2) { printf ("Filename not provided.\n"); return 1; } if((inFile=fopen(argv[1], "r"))==NULL) { printf("Can't open the file\n"); return 2; } /*obtain values for linked list*/ while (fgets(line, MAX_LINE, inFile)) { make = strtok(line, " "); yearStr = strtok(NULL, " "); stockStr = strtok(NULL, " "); year = atoi(yearStr); stock = atoi(stockStr); insertRecordInAscendingOrder(&headRecord,make, year, stock); } printf("The original list in ascending order: \n"); printList(headRecord); } /*use strcmp to compare two makes*/ int compareCars(Record *car1, Record *car2) { int compStrResult; compStrResult = strcmp(car1->make, car2->make); int compYearResult = 0; if(car1->year > car2->year) { compYearResult = 1; } else if(car1->year == car2->year) { compYearResult = 0; } else { compYearResult = -1; } if(compStrResult == 0 ) { if(compYearResult == 1) { return 1; } else if(compYearResult == -1) { return -1; } else { return compStrResult; } } else if(compStrResult == 1) { return 1; } else { return -1; } } int insertRecordInAscendingOrder(Record **head, char *make, int year, int stock) { Record *previous = *head; Record *newRecord = createRecord(make, year, stock); Record *current = *head; int compResult; if(*head == NULL) { *head = newRecord; printf("Head is null, list was empty\n"); printList(*head); return 1; } else if ( compareCars(newRecord, *head)==-1) { *head = newRecord; (*head)->next = current; printf("New record was less than the head, replacing\n"); printList(*head); return 1; } else { printf("standard case, searching and inserting\n"); previous = *head; while ( current != NULL &&(compareCars(newRecord, current)==1)) { printList(*head); previous = current; current = current->next; } printList(*head); previous->next = newRecord; previous->next->next = current; } return 1; } /*creates records from info passed in from main via insertRecordInAscendingOrder.*/ Record* createRecord(char *make, int year, int stock) { printf("CreateRecord\n"); Record *theRecord; int len; if(!make) { return NULL; } theRecord = malloc(sizeof(Record)); if(!theRecord) { printf("Unable to allocate memory for the structure.\n"); return NULL; } theRecord->year = year; theRecord->stock = stock; len = strlen(make); theRecord->make = malloc(len + 1); strncpy(theRecord->make, make, len); theRecord->make[len] = '\0'; theRecord->next=NULL; return theRecord; } /*prints list. lists print.*/ void printList(Record *head) { int i; int j = 50; Record *aRecord; aRecord = head; for(i = 0; i < j; i++) { printf("-"); } printf("\n"); printf("%20s%20s%10s\n", "Make", "Year", "Stock"); for(i = 0; i < j; i++) { printf("-"); } printf("\n"); while(aRecord != NULL) { printf("%20s%20d%10d\n", aRecord->make, aRecord->year, aRecord->stock); aRecord = aRecord->next; } printf("\n"); } The text file you'll need for a command line argument can be saved under any name you like; here are the contents you'll need: Ford 2012 15 Ford 2011 3 Ford 2010 5 Toyota 2011 7 Toyota 2012 20 Toyota 2009 2 Honda 2011 9 Honda 2012 3 Honda 2013 12 Chevrolet 2013 10 Chevrolet 2012 25 Thanks in advance for your help. I shall continue to plow away at it myself.

    Read the article

  • Strange (Undefined?) Behavior of Free in C

    - by Chris Cirefice
    This is really strange... and I can't debug it (tried for about two hours, debugger starts going haywire after a while...). Anyway, I'm trying to do something really simple: Free an array of strings. The array is in the form: char **myStrings. The array elements are initialized as: myString[index] = malloc(strlen(word)); myString[index] = word; and I'm calling a function like this: free_memory(myStrings, size); where size is the length of the array (I know this is not the problem, I tested it extensively and everything except this function is working). free_memory looks like this: void free_memory(char **list, int size) { for (int i = 0; i < size; i ++) { free(list[i]); } free(list); } Now here comes the weird part. if (size> strlen(list[i])) then the program crashes. For example, imagine that I have a list of strings that looks something like this: myStrings[0] = "Some"; myStrings[1] = "random"; myStrings[2] = "strings"; And thus the length of this array is 3. If I pass this to my free_memory function, strlen(myStrings[0]) > 3 (4 3), and the program crashes. However, if I change myStrings[0] to be "So" instead, then strlen(myStrings[0]) < 3 (2 < 3) and the program does not crash. So it seems to me that free(list[i]) is actually going through the char[] that is at that location and trying to free each character, which I imagine is undefined behavior. The only reason I say this is because I can play around with the size of the first element of myStrings and make the program crash whenever I feel like it, so I'm assuming that this is the problem area. Note: I did try to debug this by stepping through the function that calls free_memory, noting any weird values and such, but the moment I step into the free_memory function, the debugger crashes, so I'm not really sure what is going on. Nothing is out of the ordinary until I enter the function, then the world explodes. Another note: I also posted the shortened version of the source for this program (not too long; Pastebin) here. I am compiling on MinGW with the c99 flag on. PS - I just thought of this. I am indeed passing numUniqueWords to the free function, and I know that this does not actually free the entire piece of memory that I allocated. I've called it both ways, that's not the issue. And I left it how I did because that is the way that I will be calling it after I get it to work in the first place, I need to revise some of my logic in that function. Source, as per request (on-site): #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #include "words.h" int getNumUniqueWords(char text[], int size); int main(int argc, char* argv[]) { setvbuf(stdout, NULL, 4, _IONBF); // For Eclipse... stupid bug. --> does NOT affect the program, just the output to console! int nbr_words; char text[] = "Some - \"text, a stdin\". We'll have! also repeat? We'll also have a repeat!"; int length = sizeof(text); nbr_words = getNumUniqueWords(text, length); return 0; } void free_memory(char **list, int size) { for (int i = 0; i < size; i ++) { // You can see that printing the values is fine, as long as free is not called. // When free is called, the program will crash if (size > strlen(list[i])) //printf("Wanna free value %d w/len of %d: %s\n", i, strlen(list[i]), list[i]); free(list[i]); } free(list); } int getNumUniqueWords(char text[], int length) { int numTotalWords = 0; char *word; printf("Length: %d characters\n", length); char totalWords[length]; strcpy(totalWords, text); word = strtok(totalWords, " ,.-!?()\"0123456789"); while (word != NULL) { numTotalWords ++; printf("%s\n", word); word = strtok(NULL, " ,.-!?()\"0123456789"); } printf("Looks like we counted %d total words\n\n", numTotalWords); char *uniqueWords[numTotalWords]; char *tempWord; int wordAlreadyExists = 0; int numUniqueWords = 0; char totalWordsCopy[length]; strcpy(totalWordsCopy, text); for (int i = 0; i < numTotalWords; i++) { uniqueWords[i] = NULL; } // Tokenize until all the text is consumed. word = strtok(totalWordsCopy, " ,.-!?()\"0123456789"); while (word != NULL) { // Look through the word list for the current token. for (int j = 0; j < numTotalWords; j ++) { // Just for clarity, no real meaning. tempWord = uniqueWords[j]; // The word list is either empty or the current token is not in the list. if (tempWord == NULL) { break; } //printf("Comparing (%s) with (%s)\n", tempWord, word); // If the current token is the same as the current element in the word list, mark and break if (strcmp(tempWord, word) == 0) { printf("\nDuplicate: (%s)\n\n", word); wordAlreadyExists = 1; break; } } // Word does not exist, add it to the array. if (!wordAlreadyExists) { uniqueWords[numUniqueWords] = malloc(strlen(word)); uniqueWords[numUniqueWords] = word; numUniqueWords ++; printf("Unique: %s\n", word); } // Reset flags and continue. wordAlreadyExists = 0; word = strtok(NULL, " ,.-!?()\"0123456789"); } // Print out the array just for funsies - make sure it's working properly. for (int x = 0; x <numUniqueWords; x++) { printf("Unique list %d: %s\n", x, uniqueWords[x]); } printf("\nNumber of unique words: %d\n\n", numUniqueWords); // Right below is where things start to suck. free_memory(uniqueWords, numUniqueWords); return numUniqueWords; }

    Read the article

  • error while installing the libmemcached

    - by Ahmet vardar
    I get this while installing libmemcached root@server [/libmemcached]# make make all-am make[1]: Entering directory `/libmemcached' if /bin/sh ./libtool --tag=CXX --mode=compile g++ -DHAVE_CONFIG_H -I. -I. -I. -I. -I. -ggdb -DBUILDING_HASHKIT -MT libhashkit/libhashkit_libhashkit_la-aes.lo -MD -MP -MF "libhashkit/.deps/libhashkit_libhashkit_la-aes.Tpo" -c -o libhashkit/libhashkit_libhashkit_la-aes.lo `test -f 'libhashkit/aes.cc' || echo './'`libhashkit/aes.cc; \ then mv -f "libhashkit/.deps/libhashkit_libhashkit_la-aes.Tpo" "libhashkit/.deps/libhashkit_libhashkit_la-aes.Plo"; else rm -f "libhashkit/.deps/libhashkit_libhashkit_la-aes.Tpo"; exit 1; fi ./libtool: line 866: X--tag=CXX: command not found ./libtool: line 899: libtool: ignoring unknown tag : command not found ./libtool: line 866: X--mode=compile: command not found ./libtool: line 1032: *** Warning: inferring the mode of operation is deprecated.: command not found ./libtool: line 1033: *** Future versions of Libtool will require --mode=MODE be specified.: command not found ./libtool: line 1176: Xg++: command not found ./libtool: line 1176: X-DHAVE_CONFIG_H: command not found ./libtool: line 1176: X-I.: command not found ./libtool: line 1176: X-I.: command not found ./libtool: line 1176: X-I.: command not found ./libtool: line 1176: X-I.: command not found ./libtool: line 1176: X-I.: command not found ./libtool: line 1176: X-ggdb: command not found ./libtool: line 1176: X-DBUILDING_HASHKIT: command not found ./libtool: line 1176: X-MT: command not found ./libtool: line 1176: Xlibhashkit/libhashkit_libhashkit_la-aes.lo: No such file or directory ./libtool: line 1176: X-MD: command not found ./libtool: line 1176: X-MP: command not found ./libtool: line 1176: X-MF: command not found ./libtool: line 1176: Xlibhashkit/.deps/libhashkit_libhashkit_la-aes.Tpo: No such file or directory ./libtool: line 1176: X-c: command not found ./libtool: line 1228: Xlibhashkit/libhashkit_libhashkit_la-aes.lo: No such file or directory ./libtool: line 1233: libtool: compile: cannot determine name of library object from `': command not found make[1]: *** [libhashkit/libhashkit_libhashkit_la-aes.lo] Error 1 make[1]: Leaving directory `/libmemcached' make: *** [all] Error 2 OUTPUT OF ./configure checking build system type... x86_64-unknown-linux-gnu checking host system type... x86_64-unknown-linux-gnu checking target system type... x86_64-unknown-linux-gnu checking for a BSD-compatible install... /usr/bin/install -c checking whether build environment is sane... yes checking for gawk... gawk checking whether make sets $(MAKE)... yes checking for style of include used by make... GNU checking for gcc... gcc checking whether the C compiler works... yes checking for C compiler default output file name... a.out checking for suffix of executables... checking whether we are cross compiling... no checking for suffix of object files... o checking whether we are using the GNU C compiler... yes checking whether gcc accepts -g... yes checking for gcc option to accept ISO C89... none needed checking dependency style of gcc... gcc3 checking dependency style of gcc... (cached) gcc3 checking how to run the C preprocessor... gcc -E checking for grep that handles long lines and -e... /bin/grep checking for egrep... /bin/grep -E checking for ANSI C header files... yes checking for sys/types.h... yes checking for sys/stat.h... yes checking for stdlib.h... yes checking for string.h... yes checking for memory.h... yes checking for strings.h... yes checking for inttypes.h... yes checking for stdint.h... yes checking for unistd.h... yes checking minix/config.h usability... no checking minix/config.h presence... no checking for minix/config.h... no checking whether it is safe to define __EXTENSIONS__... yes checking for isainfo... no checking for g++... g++ checking whether we are using the GNU C++ compiler... yes checking whether g++ accepts -g... yes checking dependency style of g++... gcc3 checking dependency style of g++... (cached) gcc3 checking whether gcc and cc understand -c and -o together... yes checking how to create a ustar tar archive... gnutar checking whether __SUNPRO_C is declared... no checking whether __ICC is declared... no checking "C Compiler version--yes"... "gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-52)" checking "C++ Compiler version"... "g++ (GCC) 4.1.2 20080704 (Red Hat 4.1.2-52)" checking whether time.h and sys/time.h may both be included... yes checking whether struct tm is in sys/time.h or time.h... time.h checking for size_t... yes checking for special C compiler options needed for large files... no checking for _FILE_OFFSET_BITS value needed for large files... no checking for library containing clock_gettime... -lrt checking sys/socket.h usability... yes checking sys/socket.h presence... yes checking for sys/socket.h... yes checking size of off_t... 8 checking size of size_t... 8 checking size of long long... 8 checking if time_t is unsigned... no checking for setsockopt... yes checking for bind... yes checking whether the compiler provides atomic builtins... yes checking assert.h usability... yes checking assert.h presence... yes checking for assert.h... yes checking whether to enable assertions... yes checking whether it is safe to use -fdiagnostics-show-option... yes checking whether it is safe to use -floop-parallelize-all... no checking whether it is safe to use -Wextra... yes checking whether it is safe to use -Wformat... yes checking whether it is safe to use -Wconversion... no checking whether it is safe to use -Wmissing-declarations from C++... no checking whether it is safe to use -Wframe-larger-than... no checking whether it is safe to use -Wlogical-op... no checking whether it is safe to use -Wredundant-decls from C++... yes checking whether it is safe to use -Wattributes from C++... no checking whether it is safe to use -Wno-attributes... no checking for perl... perl checking for dpkg-gensymbols... no checking for lcov... no checking for genhtml... no checking for sphinx-build... no checking for working -pipe... yes checking for bison... bison checking for flex... flex checking how to print strings... printf checking for a sed that does not truncate output... /bin/sed checking for fgrep... /bin/grep -F checking for ld used by gcc... /usr/bin/ld checking if the linker (/usr/bin/ld) is GNU ld... yes checking for BSD- or MS-compatible name lister (nm)... /usr/bin/nm -B checking the name lister (/usr/bin/nm -B) interface... BSD nm checking whether ln -s works... yes checking the maximum length of command line arguments... 98304 checking whether the shell understands some XSI constructs... yes checking whether the shell understands "+="... yes checking how to convert x86_64-unknown-linux-gnu file names to x86_64-unknown-linux-gnu format... func_convert_file_noop checking how to convert x86_64-unknown-linux-gnu file names to toolchain format... func_convert_file_noop checking for /usr/bin/ld option to reload object files... -r checking for objdump... objdump checking how to recognize dependent libraries... pass_all checking for dlltool... no checking how to associate runtime and link libraries... printf %s\n checking for ar... ar checking for archiver @FILE support... @ checking for strip... strip checking for ranlib... ranlib checking command to parse /usr/bin/nm -B output from gcc object... ok checking for sysroot... no checking for mt... no checking if : is a manifest tool... no checking for dlfcn.h... yes checking for objdir... .libs checking if gcc supports -fno-rtti -fno-exceptions... no checking for gcc option to produce PIC... -fPIC -DPIC checking if gcc PIC flag -fPIC -DPIC works... yes checking if gcc static flag -static works... yes checking if gcc supports -c -o file.o... yes checking if gcc supports -c -o file.o... (cached) yes checking whether the gcc linker (/usr/bin/ld -m elf_x86_64) supports shared libraries... yes checking whether -lc should be explicitly linked in... no checking dynamic linker characteristics... GNU/Linux ld.so checking how to hardcode library paths into programs... immediate checking whether stripping libraries is possible... yes checking if libtool supports shared libraries... yes checking whether to build shared libraries... yes checking whether to build static libraries... yes checking how to run the C++ preprocessor... g++ -E checking for ld used by g++... /usr/bin/ld -m elf_x86_64 checking if the linker (/usr/bin/ld -m elf_x86_64) is GNU ld... yes checking whether the g++ linker (/usr/bin/ld -m elf_x86_64) supports shared libraries... yes checking for g++ option to produce PIC... -fPIC -DPIC checking if g++ PIC flag -fPIC -DPIC works... yes checking if g++ static flag -static works... yes checking if g++ supports -c -o file.o... yes checking if g++ supports -c -o file.o... (cached) yes checking whether the g++ linker (/usr/bin/ld -m elf_x86_64) supports shared libraries... yes checking dynamic linker characteristics... (cached) GNU/Linux ld.so checking how to hardcode library paths into programs... immediate checking whether the -Werror option is usable... yes checking for simple visibility declarations... yes checking for ISO C++ 98 include files... checking whether memcached executable path has been provided... no checking for memcached... /usr/local/bin/memcached checking whether memcached_sasl executable path has been provided... no checking for memcached_sasl... no checking whether gearmand executable path has been provided... no checking for gearmand... no checking libgearman/gearmand.h usability... no checking libgearman/gearmand.h presence... no checking for libgearman/gearmand.h... no checking for library containing getopt_long... none required checking for library containing gethostbyname... none required checking for the pthreads library -lpthreads... no checking whether pthreads work without any flags... yes checking for joinable pthread attribute... PTHREAD_CREATE_JOINABLE checking if more special flags are required for pthreads... no checking for PTHREAD_PRIO_INHERIT... yes checking the location of cstdint... configure: WARNING: Could not find a cstdint header. <stdint.h> checking the location of cinttypes... configure: WARNING: Could not find a cinttypes header. <inttypes.h> checking whether byte ordering is bigendian... no checking for htonll... no checking for working SO_SNDTIMEO... yes checking for working SO_RCVTIMEO... yes checking for supported struct padding... yes checking for alarm... yes checking for dup2... yes checking for getline... yes checking for gettimeofday... yes checking for memchr... yes checking for memmove... yes checking for memset... yes checking for pipe2... no checking for select... yes checking for setenv... yes checking for socket... yes checking for sqrt... yes checking for strcasecmp... yes checking for strchr... yes checking for strdup... yes checking for strerror... yes checking for strtol... yes checking for strtoul... yes checking for strtoull... yes checking arpa/inet.h usability... yes checking arpa/inet.h presence... yes checking for arpa/inet.h... yes checking fcntl.h usability... yes checking fcntl.h presence... yes checking for fcntl.h... yes checking libintl.h usability... yes checking libintl.h presence... yes checking for libintl.h... yes checking limits.h usability... yes checking limits.h presence... yes checking for limits.h... yes checking malloc.h usability... yes checking malloc.h presence... yes checking for malloc.h... yes checking netdb.h usability... yes checking netdb.h presence... yes checking for netdb.h... yes checking netinet/in.h usability... yes checking netinet/in.h presence... yes checking for netinet/in.h... yes checking stddef.h usability... yes checking stddef.h presence... yes checking for stddef.h... yes checking sys/time.h usability... yes checking sys/time.h presence... yes checking for sys/time.h... yes checking execinfo.h usability... yes checking execinfo.h presence... yes checking for execinfo.h... yes checking cxxabi.h usability... yes checking cxxabi.h presence... yes checking for cxxabi.h... yes checking sys/sysctl.h usability... yes checking sys/sysctl.h presence... yes checking for sys/sysctl.h... yes checking umem.h usability... no checking umem.h presence... no checking for umem.h... no checking for C++ compiler vendor... gnu checking for working alloca.h... yes checking for alloca... yes checking for error_at_line... yes checking for pid_t... yes checking vfork.h usability... no checking vfork.h presence... no checking for vfork.h... no checking for fork... yes checking for vfork... yes checking for working fork... yes checking for working vfork... (cached) yes checking for stdlib.h... (cached) yes checking for GNU libc compatible malloc... yes checking for stdlib.h... (cached) yes checking for GNU libc compatible realloc... yes checking whether strerror_r is declared... yes checking for strerror_r... yes checking whether strerror_r returns char *... yes checking for stdbool.h that conforms to C99... yes checking for _Bool... no checking for int16_t... yes checking for int32_t... yes checking for int64_t... yes checking for int8_t... yes checking for off_t... yes checking for pid_t... (cached) yes checking for ssize_t... yes checking for uint16_t... yes checking for uint32_t... yes checking for uint64_t... yes checking for uint8_t... yes checking whether byte ordering is bigendian... (cached) no checking for an ANSI C-conforming const... yes checking for inline... inline checking for working volatile... yes checking for C/C++ restrict keyword... __restrict checking whether the compiler supports GCC C++ ABI name demangling... yes checking sasl/sasl.h usability... no checking sasl/sasl.h presence... no checking for sasl/sasl.h... no checking uuid/uuid.h usability... yes checking uuid/uuid.h presence... yes checking for uuid/uuid.h... yes checking for main in -luuid... yes checking for clock_gettime in -lrt... yes checking for floor in -lm... yes checking for sigignore... yes checking atomic.h usability... no checking atomic.h presence... no checking for atomic.h... no checking for setppriv... no checking for winsock2.h... no checking for poll.h... yes checking for sys/wait.h... yes checking for fnmatch.h... yes checking for MSG_NOSIGNAL... yes checking for MSG_DONTWAIT... yes checking for MSG_MORE... yes checking event.h usability... yes checking event.h presence... yes checking for event.h... yes checking for main in -levent... yes checking for endianness... little configure: creating ./config.status config.status: creating Makefile config.status: creating docs/conf.py config.status: creating libhashkit-1.0/configure.h config.status: creating libmemcached-1.0/configure.h config.status: creating libmemcached-1.2/configure.h config.status: creating libmemcached-2.0/configure.h config.status: creating support/libmemcached.pc config.status: creating support/libmemcached.spec config.status: creating support/libmemcached-fc.spec config.status: creating libtest/version.h config.status: creating config.h config.status: config.h is unchanged config.status: executing depfiles commands config.status: executing libtool commands --- Configuration summary for libmemcached version 1.0.6 * Installation prefix: /usr/local * System type: unknown-linux-gnu * Host CPU: x86_64 * C Compiler: gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-52) * Assertions enabled: yes * Debug enabled: no * Warnings as failure: no * SASL support: --- anyone knows how to solve this ?

    Read the article

< Previous Page | 1 2 3 4 5