• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

Aikidoka

Member
So I am now rewriting my fortran code in C, and apparently I do not understand how to properly use malloc and pointers. I am trying to make the main function just nice and neat calls to other functions, which need to malloc arrays. So, I am passing pointers of pointers to them.

But the right amount of memory is not being allocated so I get segmentation faults.
Code:
#include <stdio.h>
#include <stdlib.h>
//#include <cuda.h>
#include <math.h>
//#include "cublas.h"
typedef float real;
typedef struct{
    real * amp;
} t_ampl;
typedef struct{
    int * ket;
  } blk;
typedef struct{
  int nx;
  int ny;
  int nz;
  int sz;
  int tz;
} states;

void set_SPB(real **,int,states **,states **,int **);
//void set_SPB();

const real hc =197.32697,pi=3.1415927;
int main(){
  int nmax = 2, A = 28;
   real *etemp, *fock;
  int *Ndex,*lookup,*lookup_a;
  states *channel,*SPB;

   //!generates the single particle basis to be used
  set_SPB(&etemp,nmax,&SPB,&channel,&Ndex);  
  //set_SPB();
  // set_chan(); // !organizes the SPB into proper channels
  
  // set_ph_chan(); //! ph-formalism
  
  // ini_diagrams();  //!calculates mbpt2 energy and interactions
  //CCD_iter;  !iteratively solves the CCD equations
  free(etemp);
  free(Ndex);
  free(SPB);
  
  return 0;
}
void set_SPB(real **etemp,int nmax,states **SPB,states **channel,int **Ndex){
//void set_SPB(){
  int tot_orbs = (2*nmax+1)*(2*nmax+1)*(2*nmax+1)*4;
  int D = tot_orbs/4;
  int Nalpha =  (2*nmax+1)*(2*nmax+1)*(2*nmax+1)*9;
  real E;

  *etemp = (real *) malloc(D*sizeof(float));
  *Ndex = (int *) malloc(D*3);
  *SPB = (states *) malloc(tot_orbs);
  printf("orbits without spin degeneracy %d \n",D);
  printf("size of etemp %ld \n",sizeof(*etemp)/sizeof(*etemp[0]));
  return;
  int i = 0;
  for(int nx =-nmax;nx<=nmax;nx++){
      for(int ny =-nmax;ny<=nmax;ny++){
	  for(int nz =-nmax;nz<=nmax;nz++){
	    E = 0.5*4.0*pi*pi*(nx*nx+ny*ny+nz*nz);
	    //printf("%d\n",i);
	    etemp[i] = &E;
	    Ndex[0*D+i] =&nx;
	    Ndex[1*D+i] = &ny;
	    Ndex[2*D+i] = &nz;
	    i+=1;
	    
	  }
      }
  }
  printf("Seg Fault\n");
  return;
}

The commented out function headers are where I just tried to make everything a global variable, so I didn;t have to worry about all the pointers. But that just gives the exact same error.
D above has a value of 125, so for example *etemp needs to be an array of size 125, but sizeof(*etemp)/sizeof(*etemp[0]) prints 2.
 

luoapp

Member
So I am now rewriting my fortran code in C, and apparently I do not understand how to properly use malloc and pointers

...

I think you are a bit confused about C pointer.

In function set_SPB(), etemp is a pointer to a pointer to a real variable, sizeof(*etemp) is sizeof the pointer (*etemp, usually 8), not the sizeof allocated memory. There is no easy ways to find size of a malloc'ed block. And this line etemp = &E; in C, a pointer to a variable is equivalent to an array variable, so (*etemp) would be a real array, but E is a real variable, &E doesn't make sense, I think you want (*etemp) = E; The same with Ndex[0*D+i] =&nx; , should be (*Ndex)[0*D+i] =nx;
 

Aikidoka

Member
Oh my GOD. Terrible variable names seems to be a thing in scientific computing.

I noticed the Feynman picture. Are you working on a particle physics project?

I am working on a project in Nuclear Physics.

I think you are a bit confused about C pointer.

In function set_SPB(), etemp is a pointer to a pointer to a real variable, sizeof(*etemp) is sizeof the pointer (*etemp, usually 8), not the sizeof allocated memory. There is no easy ways to find size of a malloc'ed block. And the lines after return are direct copy/paste from Fortran code, I presume? Since there are just multiple errors.

So is the malloc correct then? How should I be assigning values? It's not a direct c/p, it's just that in FORTRAN I've never used pointers.
 

luoapp

Member
I am working on a project in Nuclear Physics.



So is the malloc correct then? How should I be assigning values? It's not a direct c/p, it's just that in FORTRAN I've never used pointers.

See my edit.

This line etemp = &E; in C, a pointer to a variable is equivalent to an array variable, so (*etemp) would be a real array, but E is a real variable, &E doesn't make sense, I think you want (*etemp) = E; The same with Ndex[0*D+i] =&nx; , should be (*Ndex)[0*D+i] =nx;
 

Aikidoka

Member
See my edit.

This line etemp = &E; in C, a pointer to a variable is equivalent to an array variable, so (*etemp) would be a real array, but E is a real variable, &E doesn't make sense, I think you want (*etemp) = E; The same with Ndex[0*D+i] =&nx; , should be (*Ndex)[0*D+i] =nx;


Ok, that makes some sense (i guess). But on running it gives
*** Error in `./a.out': double free or corruption (!prev): 0x0000000001379010 ***
Aborted
When I take out the free commands, it runs without any problems. By double free, I imagine something is going wrong with the arrays or I'm using the free command incorrectly as well?
 

Daffy Duck

Member
Hi,

I need some guidance, the company I work for has a client who is potentially looking at having an app built, the scope of the app at this present time would only be something that people click and it takes them to a mobile optimised version of a website, is this possible on iOS & Android? How is this handled? Will it just launch Safari/browser or will it launch an app and then fit the browser to this?

In order to submit this app to the app store do we have to be app developers? Currently the company I work at are not app developers.

Sorry for the newbie questions, but this is literally the first time we have been asked to do this, and I know little about this as you can tell, and I will have to explain it and the costs involved to my boss (who is a complete luddite and knows nothing about this sort of thing).
 

Aikidoka

Member
Alright, now I'm getting warnings when trying to malloc the array in the struct that is apart of an array of the structs. Maybe it's not a big deal in C but I'd at least like to get some clarification for future reference. i've basically just been trying different combinations of '*' and parentheses.

Here is how the struct is defined, passed, and malloc'd.
Code:
typedef struct{
  
  int *ket;
  
} blk;
// in function main hole var is defined and passed by:
int main(){
blk *hole;
func(&hole);
}
... // in func() i have the malloc statements
 *hole = malloc(sizeof(**hole)*Nalpha);
....
 *(*hole)[alpha].ket=malloc(dimalpha*2*sizeof(*(*hole)[alpha].ket));
//also assigning via:
int  DIM = (*size_hole)[alpha];
  (*hole)[alpha].ket[dimalpha+0*DIM] = ii

The compiler issues the warning
warning: assignment makes integer from pointer without a cast [enabled by default]
*(*hole)[alpha].ket=malloc(dimalpha*2*sizeof(*(*hole)[alpha].ket));
 

luoapp

Member
*(*hole)[alpha].ket=malloc(dimalpha*2*sizeof(*(*hole)[alpha].ket));

(*hole)[alpha].ket is a pointer to an integer, *(*hole)[alpha].ket is that integer, and you try to assign a pointer to it.

You really should trim down the use of *, even just for readability's sake, you can have at least rid of one level.
 

Aikidoka

Member
*(*hole)[alpha].ket=malloc(dimalpha*2*sizeof(*(*hole)[alpha].ket));

(*hole)[alpha].ket is a pointer to an integer, *(*hole)[alpha].ket is that integer, and you try to assign a pointer to it.

You really should trim down the use of *, even just for readability's sake, you can have at least rid of one level.
I thought in order for other functions to be able to use this, I need to append extra pointers to everything. Essentially to pass the pointers by reference.
 

luoapp

Member
I thought in order for other functions to be able to use this, I need to append extra pointers to everything. Essentially to pass the pointers by reference.

Just having something like
int t = *pointer;
at the beginning helps with the readability, which is as important as your algorithm, especially when your code grows bigger.
 

Aikidoka

Member
*(*hole)[alpha].ket=malloc(dimalpha*2*sizeof(*(*hole)[alpha].ket));

(*hole)[alpha].ket is a pointer to an integer, *(*hole)[alpha].ket is that integer, and you try to assign a pointer to it.

You really should trim down the use of *, even just for readability's sake, you can have at least rid of one level.

if *(*hole)[alpha].ket is the integer array, how can I access the individual elements and assign them.
My compiler does not like *(*hole)[alpha].ket[0] = ii

I would like for everything to be more readable for sure, but this code just needs to get done ASAP and is just a prototype version to see if CUDA will have much of an effect.

EDIT: Ok Nevermind, perhaps (*hole)[alpha].ket[0] = ii does work. The segmentation fault wasn't at the line I thought.
 

traveler

Not Wario
This is not really a programming question, but I can't believe I can't find a simple answer to this- what is the best way to just do a simple find and replace on a large .tab file in Windows? I tried doing it with Excel but it totally screwed the format and I've been told other windows based products will do the same. I tried Sublime but it can't handle doing a find and replace on a file of this size. Going to keep googling but figured i'd ask here for whatever it's worth.
 
Hi,

I need some guidance, the company I work for has a client who is potentially looking at having an app built, the scope of the app at this present time would only be something that people click and it takes them to a mobile optimised version of a website, is this possible on iOS & Android? How is this handled? Will it just launch Safari/browser or will it launch an app and then fit the browser to this?

In order to submit this app to the app store do we have to be app developers? Currently the company I work at are not app developers.

Sorry for the newbie questions, but this is literally the first time we have been asked to do this, and I know little about this as you can tell, and I will have to explain it and the costs involved to my boss (who is a complete luddite and knows nothing about this sort of thing).

Why would you need an app for this? Wouldn't you just want your site to detect if its a mobile browser and load the correct version?

On iOS you could just package your web page content in an app and load it all in a UIWebView, but this is frowned upon by Apple. I did some projects like this for corporate clients where the app wasn't put on the App store, but if its something that is gonna be public facing I don't think you can get away with it.
 

luoapp

Member
This is not really a programming question, but I can't believe I can't find a simple answer to this- what is the best way to just do a simple find and replace on a large .tab file in Windows? I tried doing it with Excel but it totally screwed the format and I've been told other windows based products will do the same. I tried Sublime but it can't handle doing a find and replace on a file of this size. Going to keep googling but figured i'd ask here for whatever it's worth.

Notepad++, how big is your file?
 

OceanBlue

Member
This is not really a programming question, but I can't believe I can't find a simple answer to this- what is the best way to just do a simple find and replace on a large .tab file in Windows? I tried doing it with Excel but it totally screwed the format and I've been told other windows based products will do the same. I tried Sublime but it can't handle doing a find and replace on a file of this size. Going to keep googling but figured i'd ask here for whatever it's worth.
I've opened a 2gb file in Vim before. Sublime and Notepad++ just froze up.
 

Daffy Duck

Member
Why would you need an app for this? Wouldn't you just want your site to detect if its a mobile browser and load the correct version?

On iOS you could just package your web page content in an app and load it all in a UIWebView, but this is frowned upon by Apple. I did some projects like this for corporate clients where the app wasn't put on the App store, but if its something that is gonna be public facing I don't think you can get away with it.

That is exactly my reasoning on this, but the client is of the mindset "I want an app", someone has spoken to him already and explained app develoment isn't cheap and this is what they have come up, I am yet to be involved in the discussions. I am also facing an uphill struggle in the fact that because of the client wishes my boss will not simply accept my answer of it's best to just make the website responsive (which it will be anyway) and not bther with an app, he will be stubborn over it (and to compound the problem he is not computer/app literate in the slightest).

It will most definitely be public facing.
 

Koren

Member
This is not really a programming question, but I can't believe I can't find a simple answer to this- what is the best way to just do a simple find and replace on a large .tab file in Windows?
sed (easy to find for Windows)

Really. You shouldn't have to open a file for a replace.

Take a couple minutes to learn its syntax, it's a wonderful tool to have handy. If you post the replace you want to perform, we can give you the command.
 

Pau

Member
Building a small program in Python but I'm a bit confused about variable access. Are class attributes global?

For example, I have these two functions:

Code:
def raise_frame(frameToRaise, frameToForget):
	frameToRaise.tkraise()
	frameToForget.grid_forget()

def char1Display():
	prompt1 = Label(char1Frame, text="Character name:")
	prompt1.pack()
	singleCharEntry = AutocompleteEntry(char1Frame, bd=5)
	singleCharEntry.set_completion_list(charNamesList)
	singleCharEntry.pack()
	singleCharEntry.focus_set()
	submitSingle = Button(char1Frame, text="Enter", command=lambda: raise_frame(singleChar, startScreen))
	submitSingle.pack()

When you click the submit button, I want it to raise a frame while also accessing whatever the user input into singleCharEntry. However, I can't call singleCharEntry anywhere else because it's local to this function so I can't just sneak in a singleCharEntry.get() into the raise_frame function. Would using a class solve this? Should the class have both the char1Display and the raise_frame functions?
 

poweld

Member
Building a small program in Python but I'm a bit confused about variable access. Are class attributes global?

When you click the submit button, I want it to raise a frame while also accessing whatever the user input into singleCharEntry. However, I can't call singleCharEntry anywhere else because it's local to this function so I can't just sneak in a singleCharEntry.get() into the raise_frame function. Would using a class solve this? Should the class have both the char1Display and the raise_frame functions?

It sounds like you want to access singleCharEntry from raise_frame, but singleCharEntry is a locally scoped variable (only accessible from within that function). You could use a class, as you mentioned, to store that value in a member variable.

If I'm mistaken, you may need to provide more context to the problem.
 

NotBacon

Member
This is not really a programming question, but I can't believe I can't find a simple answer to this- what is the best way to just do a simple find and replace on a large .tab file in Windows? I tried doing it with Excel but it totally screwed the format and I've been told other windows based products will do the same. I tried Sublime but it can't handle doing a find and replace on a file of this size. Going to keep googling but figured i'd ask here for whatever it's worth.

Good ol'
:%s/find/replacement/gc
in Vim
 
Speaking of Vim, finally got Syntastic and NERDTree running in mine. Also have it set up to highlight ERROR/WARN/INFO automatically for reading log files. Also discovering more about the help system and buffers/tabs.

Truly a wonderful editor that continues to amaze me in how many things it can do/handle.
 

Ambitious

Member
Gotta work on an Eiffel project for a university course. The IDE we're using is called EiffelStudio.

The output console in this IDE is a separate window. The title bar says: "EiffelStudio Console (Do not Close)". Uh, that's a weird warning. So what happens when I do actually close it? An UncaughtException error message appears for two seconds before EiffelStudio completely crashes.

Huh.
 
Gotta work on an Eiffel project for a university course. The IDE we're using is called EiffelStudio.

The output console in this IDE is a separate window. The title bar says: "EiffelStudio Console (Do not Close)". Uh, that's a weird warning. So what happens when I do actually close it? An UncaughtException error message appears for two seconds before EiffelStudio completely crashes.

Huh.

Amazing. I'd have a word or 2 with your course teacher if I was in that situation xD.
I'm finally wrapping my head around F#, turns out I just needed the right tutorial. I kind of want to try making a webapp with it.
 

Jokab

Member
Sup guys, I'm having some regex troubles with my current school project (this is not homework, it's a project). Using Python 2.7 if that matters.

Basically what I'm trying to do is to capture inserted variables in a PHP SQL query string declaration, for example:

Code:
$query  = "SELECT * FROM `users` WHERE user='$user' AND password='$pass';";

This should return $user when I get the second group from the match.

Here's my regex as it stands right now:
Code:
r'.*?\s*=\s*\(\".*?\'(\$[^\']+)\'.*?\"\);'
Example showing that this works and captures $user (yes I know it doesn't capture $pass, that's seems to be a limitation with Python's implementation and Regex in general. I do some hacks to get around this in my actual program)

The above works for the example I used. However, when I introduce another case where the inserted variable uses the syntax '{$foo['bar']}', my other regex below doesn't work which accounts for the fact that it contains an apostrophe which doesn't close the variable:
Code:
r'.*?\s*=\s*[\(]?\".*?(?:(?:\'(\$[^\']+)\')|(?:\'(\$\{[^\}]+\})\'))?.*?\"[\)]?;'
So basically I want to capture either the '$user' syntax or the one with { }.

Here's a link to test this out. Using the second regex also breaks capturing the simple $user, not sure why.
 

Kieli

Member
Hey, anyone have good resources for learning about databases/SQL, data structures, and algorithms?

For example, my university has course webpages with all lecture notes, assignments, labs, etc...

I'm also trying to self-learn Python, PHP, and JavaScript. Hope to gain some measure of competency over the summer.
 

Somnid

Member
Sup guys, I'm having some regex troubles with my current school project (this is not homework, it's a project). Using Python 2.7 if that matters.

Basically what I'm trying to do is to capture inserted variables in a PHP SQL query string declaration, for example:

Code:
$query  = "SELECT * FROM `users` WHERE user='$user' AND password='$pass';";

This should return $user when I get the second group from the match.

Here's my regex as it stands right now:
Code:
r'.*?\s*=\s*\(\".*?\'(\$[^\']+)\'.*?\"\);'
Example showing that this works and captures $user (yes I know it doesn't capture $pass, that's seems to be a limitation with Python's implementation and Regex in general. I do some hacks to get around this in my actual program)

The above works for the example I used. However, when I introduce another case where the inserted variable uses the syntax '{$foo['bar']}', my other regex below doesn't work which accounts for the fact that it contains an apostrophe which doesn't close the variable:
Code:
r'.*?\s*=\s*[\(]?\".*?(?:(?:\'(\$[^\']+)\')|(?:\'(\$\{[^\}]+\})\'))?.*?\"[\)]?;'
So basically I want to capture either the '$user' syntax or the one with { }.

Here's a link to test this out. Using the second regex also breaks capturing the simple $user, not sure why.

Not actually sure what you're doing here but a few thoughts:

1) SQL injection. If you're planning to replace these values you're very likely going to have SQL inject issues. Use an existing library that can do this safely.
2) If your reading values out, regexs likely are not flexible enough to handle all cases, you need to be able to parse SQL.
3) If $user is just for token replacement then make it easier to parse without needing to understand the grammar, like ${user} etc.
 

Jokab

Member
Not actually sure what you're doing here but a few thoughts:

1) SQL injection. If you're planning to replace these values you're very likely going to have SQL inject issues. Use an existing library that can do this safely.
2) If your reading values out, regexs likely are not flexible enough to handle all cases, you need to be able to parse SQL.
3) If $user is just for token replacement then make it easier to parse without needing to understand the grammar, like ${user} etc.

It's for a school project where the idea is to search through GitHub PHP code and find how much of it that doesn't employ basic protections like prepared statements and escaped strings. To do that, the idea is this:
1. Find SQL query strings in PHP (look at mysql_query or mysqli_query calls and see what is put in there)
2. In the SQL strings, find PHP variables denoted by '$var'
3. If this variable is assigned using either $_GET or $_POST, it most likely came from the user
4. If the variable is not escaped in any way and came directly from the user into a query, the query is likely vulnerable to SQL injection

This is obviously a very simple way of finding (only one way of) SQL injection vectors, but nevertheless I think it can show how poorly code is protected against SQL injections; which is obviously the case, but some type of evidence is required.
 

D4Danger

Unconfirmed Member
Code:
\w+\=['\"](\$\w+|\{\$[\w\[\'\"]+\]\})

Match 1
1.	{$_DVWA['db_database']}
Match 2
1.	$user
Match 3
1.	$pass

something like that?
 

Jokab

Member
Code:
\w+\=['\"](\$\w+|\{\$[\w\[\'\"]+\]\})

Match 1
1.	{$_DVWA['db_database']}
Match 2
1.	$user
Match 3
1.	$pass

something like that?

Thank you for the contribution, it did get me part of the way there. What I ended up doing was split the regexing into two steps: first find the SQL string, then capture inside it. Solved a lot of issues I was having with the results.
 
Have an interview with a company tomorrow, a more technical interview. I am reviewing some general OOP principles and some Java specific features. Any additional advice? I am a bit nervous. Technical programming interviews are either very general and basic or harder than the job itself.
 
Last day of my programming class. I have a 95% so far, but the final is worth 40% of my grade and I only got like 10/18 in the multiple choice portion. I think I will do much better in the portions that are yet ungraded, but I'm still nervous. Not that I will fail, but in the off chance I bomb then I have to pay my tuition assistance back...
 

poweld

Member
Have an interview with a company tomorrow, a more technical interview. I am reviewing some general OOP principles and some Java specific features. Any additional advice? I am a bit nervous. Technical programming interviews are either very general and basic or harder than the job itself.

Don't drink too much coffee. Keep water on hand. Talk your way through your problems. Implement a naive and flawed solution first if it's easy (acknowledging it's naive) before attempting to find the optimal solution.
 
Top Bottom