This is with ref to the code http://wind.d.umn.edu/acmclub/sites/default/files/summation.cu provided at http://wind.d.umn.edu/acmclub/?q=node/12
Im a beginner programmer but still I could follow the code and explanation except for few things.
1.] What is the meaning of "new" in this line taken from summation.cu
sum_h = new unsigned long();
2.]Also I really couldnt understand this code. What purpuse does strtoul serve ? I'd be thankful if you could point to some beginners resource on "new" & "strtoul"
n = strtoul(argv[1], NULL, 0);
3.] Is the code "summation.cu" written completely in C++. So inorder to code CUDA programs do I need to learn C++ instead of C? Or do I need to learn both C & C++ ?
To make it short:
new allocates memory (e.g. for the sum) (see details)
strtoul converts a string to a long (see details)
I think you should start with a good C++ book (e.g. C++ Primer) and learn some C later (e.g. from this book). After that I would start with
CUDA.
Keep your chin up.
As Saviour Self pointed out in the comments - new means dynamic memory allocation on the heap at runtime. More information here.
I think this is pretty much similar to the C-function atoi that converts a number stored as a char into a integer. In you case this should convert the number (stored as char) in argv[1] into a unsigned long int. Check it here.
The language used in CUDA is called "C for CUDA" and as long as I've been reading and learning you can code in C but there are many features of C++ that are also supported. You can start taking a look at CUDA DOCUMENTATION.
Hope this helps.
Related
I'm writing a program in CAPL (which is based on C and minus some concepts) to convert a string containing a number displayed in scientific notation to a float (doesn't strictly need to be a float but I think its an appropriate type for this). For example:
-7.68000000E-06 should be converted to -0.00000768
I've done some looking around for this and atof() comes up a lot but this is not supported in CAPL so I cannot use that.
A list of the other C concepts not supported in CAPL:
Update: Thanks everyone for the help. M. Spiller's answer proved to be the easiest solution. I have accepted this answer.
In CAPL the function is called atodbl with the same signature as C's atof.
I am currently learning embedded programming, and thus working on an IAR-platform using a TI microcontroller with ARM architecture. Since I am not at all familiar with the technicalities related to this kind of programming, or C programming in general, I would like to ask a basic question:
I have the following simple code snippet:
int i;
for(i = 0; i < NUM_SAMPLES; i++)
{
sinTable[i] = sinf(2*i*dT*PI);
}
for(i = 0; i < NUM_SAMPLES; i++)
{
char out[32];
sprintf(out,"sin: %.7f, %.7f;", i*dT, sinTable[i]);
putString(out);
delay(DELAY_100US);
}
Where sinTable[] is a global variable of size NUM_SAMPLES, putString(*char) is a function which writes to an RS232-port, and delay(float) is a simple delay-function.
My problem is that once the sprintf(...) is called, it corrupts sinTable, giving some very peculiar results when plotting the table on the receiver end of the COM-signal.
I don't expect that I run out of memory, as the MC has 64KB SRAM.
Does anyone have any thoughts?
Ensure that your stack pointer is on a 64-bit boundary when main is reached.
The symptom your are seeing is typical of a stack aligned on an odd 32-bit boundary. Everything seems to work properly until a double is used as a variadac argument. This breaks when the code expects such arguments to be on 8-byte boundaries.
Upon further review:
I suspect that Michael Burr's response regarding stack utilization was on the right track. Selecting a smaller printf library might be sufficient, but if you can increase your stack size, that seems safer. Note that the IAR C/C++ Development Guide includes info on linker stack usage analysis.
Original:
When I upgraded from IAR 6.1 (licensed) to 6.4 (kickstart), I ran into a similar problem - vsnprintf was writing "all over RAM", even though the return value indicated the number of characters written was well within the target bounds. The "solution" was to avoid the printf library that has multibyte support.
Project Options > General > Library Options > printf small w/o multi-byte
might want to also uncheck
Project Options > C/C++ Compiler / Language 2 / enable multibyte
I tried to report this to IAR, but since my support contract is expired ...
Unfortunately, a similar problem is back with IAR 7.3.4, and the multibyte "fix" does NOT seem to be sufficient. Happens with both sprintf() and snprintf(), although the out-of-bounds corruption is not identical between those 2.
You seem pretty confident that your result string is only 31 characters long. The only way to corrupt another variable with your sprintf statement is that your result string is longer than 32 bytes (31 chars and a nul-byte), therefore overwriting other parts of memory. Make your numbers smaller or make your temporary buffer larger.
Thank you to anyone who have suggested a solution to this problem. I eventually ended up writing a conversion method that gives a hex-representation of the string and transmitted that instead, omitting the sprintf(...) completely.
It is very crude, but suits my needs.
I'm trying to organize a programming contest for signal processing; originally it was going to be in Python, but the question came up if I could expand allowable entries to C.
The type of programming needed for the entries is really pretty limited:
no stdin/stdout needed
contestants can declare 1 struct containing state variables
entries can declare functions
I will create my own trusted C code for a test harness that calls into the contestants' entries
So I am wondering:
is it possible to declare a particular C file as "safe" by parsing, if there are severe restrictions on the type of calculations allowed? The one thing I can't seem to figure out is how to easily prevent casting pointers or pointer arithmetic.
Entries would be of this form (more or less):
#include "contest.h"
// includes stdint.h and math.h and some other things
// no "#" signs after this line allowed
typedef struct MyState {
int16_t somevar;
int16_t anothervar;
...
} MyState_t;
void dosomething(MyState *pstate)
{
...
}
void dosomethingelse(MyState *pstate)
{
...
}
void calculate_timestep(MyState *pstate, ContestResults *presults)
{
...
}
I've read some of the sandboxing questions (this and this) and it looks a bit difficult to find a way to sandbox one part of C code but allow other trusted parts of C code. So I'm hoping that parsing may be able to help "bless" C code that meets certain constraints.
Any advice? I don't really care if it gets stuck in an infinite loop (I can kill it if the time takes too long) but I do want to prevent OS access or unwanted memory access.
There's no point in allowing C if you also want to disallow things that are part of C, such as pointers, casting, and pointer arithmetic. Many valid C programs then become impossible to write, which would seem counter-intuitive if you're saying "you can use C".
It's hard to detect statically that a program won't do
*(uint32_t *) 0 = 0xdeadf00d;
which might cause a segmentation fault on your host operating system. I'm sure it's possible, or that very good attempts have been made. This Wikipedia article has a list of C and C++ static checking tools that you can investigate.
I am new to prolog. I have learned that ,though it is a declarative language, prolog can be used as a general purpose programming language, just like C. So, whatever problems you can solve in C, you can solve in prolog as well, even though its run-time may not be as good. Since there are no pointers in prolog (as far as i know), I am wondering if i can write an equivalent program in prolog for the following code written in C :-
#include <stdio.h>
int main()
{
int a = 5;
int *p;
p = &a;
printf("The address of a is %d.", p);
return 0;
}
You're trying to drive in a nail using a screwdriver, to use a popular analogy. Prolog is not C and solving problems in Prolog is fundamentally different from solving them in C.
Printing the value of a variable is easy to do, for example:
main :-
X = 5,
io:format("X = ~w~n", [X]).
but you can't get the address of X like you can in C. And why would you want to? The address could be different next time since Prolog has automatic garbage collection.
If you want to learn Prolog, forget about trying to write Prolog programs which look like C programs, and try to solve actual problems instead. You could try out the Project Euler series of problems, for example.
Apart from the comments and the existing answer, here is more:
Ask yourself: what is the use of the C program that you have shown? What problem does it solve? I can't answer this question, and I suspect you can't answer it either. In isolation, this program has no useful application whatsoever! So despite C being a general purpose programming language, you can write programs without any purpose, general or domain-specific.
The same, of course, is true of Prolog.
To pointers in particular: they are a very thin abstraction over absolute memory addresses. You can use (and abuse) pointers in many ways, and, if your algorithms are correct for the problem you are currently solving, the compiler can generate very efficient machine code. The same, however, is true of Prolog. The paradigms, however, will be very different.
In summary, you have managed to write a question so devoid of meaning that you provoked me to answer it without any code.
P.S. Or you have just trolled us with moderate success.
Well, since you tagged swi-prolog your question, I can show the code I used to exchange Qt GUI objects (just pointers, you know...) with the Prolog engine.
/** get back an object passed by pointer to Prolog */
template<typename Obj> Obj* pq_cast(T ptr) {
return static_cast<Obj*>(static_cast<void*>(ptr));
}
to be used, for instance in swipl-win, where _read_f is really a C callback:
/** fill the buffer */
ssize_t Swipl_IO::_read_f(void *handle, char *buf, size_t bufsize) {
auto e = pq_cast<Swipl_IO>(handle);
return e->_read_(buf, bufsize);
swipl-win has found its way as the new console in SWI-Prolog.
I have used several dynamically typed languages and I have been avoiding C but enough is enough, it's the right tool for the job sometimes and I need to get over it.
The things I miss working with C are associative arrays and large string libraries. Is there a library that gives more options then string.h? Any general advice when it comes to make the transition with strings?
Thanks for reading-Patrick
You can take a look at the Better String Library. The description from the site:
The Better String Library is an
abstraction of a string data type
which is superior to the C library
char buffer string type, or C++'s
std::string. Among the features
achieved are:
Substantial mitigation
of buffer overflow/overrun problems
and other failures that result from
erroneous usage of the common C string
library functions
Significantly
simplified string manipulation
High
performance interoperability with
other source/libraries which expect
'\0' terminated char buffers
Improved
overall performance of common string
operations
Functional equivalency with
other more modern languages
The
library is totally stand alone,
portable (known to work with gcc/g++,
MSVC++, Intel C++, WATCOM C/C++, Turbo
C, Borland C++, IBM's native CC
compiler on Windows, Linux and Mac OS
X), high performance, easy to use and
is not part of some other collection
of data structures. Even the file I/O
functions are totally abstracted (so
that other stream-like mechanisms,
like sockets, can be used.)
Nevertheless, it is adequate as a
complete replacement of the C string
library for string manipulation in any
C program.
POSIX gives you <string.h>, <strings.h> and <regex.h>.
If you really need more of a string library than this, C is probably not the right tool for that particular job.
As for a hash table, you can't get a type-safe hash table in C without a lot of nasty macros.
If you're OK with just storing void-pointers, or with doing some manual work for each type of map, then you shouldn't be lacking for options. Coding your own hash table is a hoot and a half - just search Stackoverflow for help with the hash function. If you don't want to roll your own, strmap [LGPL] looks decent.
GLib provides many pre-made data structures and string handling functions, but it's a set of functions and types completely separated from the "usual" ones, and it's not a very lightweight dependency.
If instead C++ is a viable alternative for your task, it bundles a string class and several generic containers ready-made into the standard library (and much other related stuff can be found in Boost).
What specifically are you looking for in your extended c-string library?
One way to get better at C, is to create your own c-string library. Then make it open source, and let others help refine it.
I don't usually advocate creating your own string libaries, but w.r.t. C, it's a great way to learn C.
Much of the power of C consists of the ability to have direct control over the memory as a sequence of bytes. It is a bit against the philosophy of the language to treat strings as something higher-level than that.
I would recommend rolling your own very basic one. It will be an enlightening experience especially to learn pointer arithmetics and loops.
For example, learn about "Schlemiel the Painter's algorithm" regarding strcat and design your library to solve this problem.
I've not used it myself, but you should at least review the SEI/CERT library Specifications for Managed Strings, 2nd Edition. The code can be found at CERT.
An associative array associating string keys and struct values in C consists of:
A hash function for strings
An array with a prime number of elements, inside each of which is a linked-list head.
Linked-list elements containing char * pointers to the stored keys and (optionally) a struct * pointer to the corresponding value for each key.
To store a string key in your associative array:
Hash it modulo that prime array size.
In that array bin, add it to the linked-list.
Assign the value pointer to the value you are adding.