Why I can't malloc function in between a code given below?? PS:- COMMENT LINES - malloc

why can't i declarer a new variable in the 4th linen using malloc function
compiler gives an error "Cannot create a new node".
while(a>0)
{ struct node*newnode=(struct node*)malloc(sizeof(struct node*));
printf("Enter the data in the node\n");
scanf("%d",&b);
struct node*newnodee=(struct node*)malloc(sizeof(struct node*));
newnode->data=b;

"#include studio.h>"
"#include stdlib.h>"
These library should be included in your files.

Related

Problems using malloc in D language: why writeln call the destructor twice in this example

I am trying to write a D wrapper for a C library (libmpdec) that stores its data using the standard C malloc function. But the are
some nasty bugs in my programs that I don't know how to solve.
So I have written the following test example, trying to understand this. The idea is to create structure holding a pointer to a memory area allocated using malloc in the constructor and that contains a zero-terminated C string, and free the area using the destructor. Also I can print the string using printf. The problem arises when I try to implement a method toString() so that I can use the standard D function writeln. For some reason that I don't understand the destructor seems to be called twice! (one after writeln) and so a segmentation fault occurs.
import std.stdio;
import core.stdc.stdlib;
import std.string;
import core.stdc.string;
struct Prueba {
char* pointer;
string name;
this(string given_name)
{
writeln("calling the constructor");
pointer= cast (char*) malloc(char.sizeof*10);
name=given_name;
char* p= pointer;
*p= 'a';
p++;
*p= 'b';
p++;
*p= '\n';
p++;
*p= '\0';
}
~this()
{
writeln("\n calling the destructor");
free(pointer);
}
void print()
{
printf("Using printf %s \n",pointer);
}
string toString()
{
ulong len=strlen(pointer);
return cast(string) pointer[0..len];
}
}
void main()
{
writeln("version 1");
Prueba p=Prueba("a");
writeln("using writeln ",p);
p.print();
}
But if I store the result in a string varible like
string s=p.toString();
writeln("using writeln ",s);
The program just works! I cannot figure out why!
You can see both versions of my test program at
https://github.com/pdenapo/example_programs_in_D/tree/master/using_malloc
Many thanks for any help!
Update: It seems that writeln plays no role here. And I can get the
same result with something like
void probando(Prueba q)
{
q.print();
}
probando(p);
The problem seems to be that a copy of p is created when calling a function.
In cases like this, it's often a good idea to see if it's the same instance being destroyed. Adding &this to the writeln calls, I get this output:
version 1
calling the constructor at 6FBB70F960
Instance on stack: 6FBB70F960
using writeln ab
calling the destructor at 6FBB70F820
calling the destructor at 6FBB70F7F0
As we can see, the pointers are different, so there's two instances.
D structs are value types, and so are copied and moved. When you call a function taking a class parameter, a pointer is what's actually being passed, and it basically says 'the class instance you're looking for is over there'. With structs a copy is created, and suddenly you have two independent objects living their separate lives.
Of course, that's not what you want - Prueba isn't actually a copyable type, since having two copies will result in two calls to the destructor, and thus double freeing. To mark it as non-copyable, simply add #disable this(this); to disable the postblit, and the compiler will helpfully throw error messages at you when a copy would be created.
This will cause a compiler error on the writeln line, and you will have to manually call toString, e.g.: writeln("using writeln ", p.toString());
Note that a non-copyable struct may be passed to functions as ref, since that doesn't create a new copy. We can't really modify writeln to do that, but it's worth knowing for your own functions.

How to access the /proc file system's iiterate function pointer

I am trying to create a simple linux rootkit that can be used to hide processess. The method I have chosen to try is to replace the pointer to "/proc" 's iterate function with a pointer to a custom one that will hide the processess I need. To do this I have to first save a pointer to it's originale iterate function so it can be replaced later. The '/proc' file system's iterate function can be accessed by accessing the 'iterate' function pointer which is a member of it's 'file_operations' structure.
I have tried the following two methods to access it, as can be seen in the code segment as label_1 and label_2, each tested with the other commented out.
static struct file *proc_filp;
static struct proc_dir_entry *test_proc;
static struct proc_dir_entry *proc_root;
static struct file_operations *fs_ops;
int (*proc_iterate) (struct file *, struct dir_context *);
static int __init module_init(void)
{
label_1:
proc_filp = filp_open("/proc", O_RDONLY | O_DIRECTORY, 0);
fs_ops = (struct file_operations *) proc_filp->f_op;
printk(KERN_INFO "file_operations is %p", fs_ops);
proc_iterate = fs_ops->iterate;
printk(KERN_INFO "proc_iterate is %p", proc_iterate);
filp_close(proc_filp, NULL);
label_2:
test_proc = proc_create("test_proc", 0, NULL, &proc_fops);
proc_root = test_proc->parent;
printk(KERN_INFO "proc_root is %p", proc_root);
fs_ops = (struct file_operations *) proc_root->proc_fops;
printk(KERN_INFO "file_operations is %p", fs_ops);
proc_iterate = fs_ops->iterate;
printk(KERN_INFO "proc_iterate is %p", proc_iterate);
remove_proc_entry("test_proc", NULL);
return 0;
}
As per method 1, I open '/proc' as a file, then follow the file pointer to access it's 'struct file_operations' (f_op), and then follow this pointer to try and locate 'iterate'. However, although I am able to successfully access the 'f_op' structure, somehow it's 'iterate' seems to point to NULL. The following dmesg log shows the output of this.
[ 47.707558] file_operations is 00000000b8d10f59
[ 47.707564] proc_iterate is (null)
As per method 2, I create a new proc directory entry, then try to access it's parent directory (which should point to '/proc' itself), and then try to access it's 'struct file_operations' (proc_fops), and then try to follow on to 'iterate'. However, using this method I am not even able to access the '/proc' directory, as 'proc_root = test_proc->parent;' seems to return NULL. This causes a 'kernel NULL pointer dereference' error in the code that follows. The following dmesg log shows the output of this.
[ 212.078552] proc_root is (null)
[ 212.078567] BUG: unable to handle kernel NULL pointer dereference at 000000000000003
Now, I know that things have changed in the linux kernel, and we are not allowed to write at various addresses (like change the iterate pointer to point at a custom function for example) and that this can be overcome by making those pages writable in the kernel, but that will come later in my attempt to create this rootkit. At present I can't even figure out how to even read the original 'iterate' pointer.
So, I have these questions :
[1] Is something wrong in the following code ? How to fix it ?
[2] Is there any other way to access the pointer to the /proc 's iterate function ?
Tested on Arch Linux running linux 4.15.7

cgo C struct field access from Go: underscore or no underscore?

I'm running into a disconnect between the online documentation and the behavior I see in my programs accessing C structs within GO code. go version says I am using:
go version go1.4.2 linux/amd64
According to the GO CGO documentation:
Within the Go file, C's struct field names that are keywords in Go can be
accessed by prefixing them with an underscore: if x points at a C struct with
a field named "type", x._type accesses the field. C struct fields that cannot
be expressed in Go, such as bit fields or misaligned data, are omitted in the
Go struct, replaced by appropriate padding to reach the next field or the end
of the struct.
I had troubles with this, so made a quick sample program to test it out:
package main
// struct rec
// {
// int i;
// double d;
// char* s;
// };
import "C"
import "fmt"
func main() {
s := "hello world"
r := C.struct_rec{}
r.i = 9
r.d = 9.876
r.s = C.CString(s)
fmt.Printf("\n\tr.i: %d\n\tr.d: %f\n\tr.s: %s\n",
r.i,
r.d,
C.GoString(r.s))
}
When I use underscores as the docs indicate (eg, substitute r._i for r.i above) I get the following compile error:
r._i undefined (type C.struct_rec has no field or method _i)
When I don't use underscores it works fine. I tried this with both pointers and non-pointers. The only other idea I can think of is that maybe it's because I allocated the instances in GO rather than C, is that the case??
Thanks for any help!
The answer is in the very quote you have in your question:
Within the Go file, C's struct field names that are keywords in Go can be accessed by prefixing them with an underscore(…)
i, d, and s are not keywords in Go.

I am not able to link 2 .cpp files with a header in visual studio

I have a file p2.cpp and 2d.cpp which I'm trying to link with 2d.h.
I have included 2d.h in both .cpp files and I'm getting an error:
2d.obj : error LNK2005: "float (* v)[3]" (?v##3PAY02MA) already defined in p2.obj
1: fatal error LNK1169: one or more multiply defined symbols found.
What should I do?
I have a file p2.cpp and 2d.cpp which I'm trying to link with 2d.h. I
have included 2d.h in both .cpp files and I'm getting an error:
Each symbol may only be defined in a program once (refer One definition rule). I'm not sure what you're header file looks like, but typically this means something to the effect of defining something in you're header file that is included in more than one compilation unit. You could "extern" it in you're header, and ensure that it is defined in a separate compilation unite.
From the compiler error it looks like you've define an array of pointers to functions in your header file. Extern this and provide a single definition in a source file.
This code effectively causes the problem:
//--- Def.h
#ifndef DEF_H
#define DEF_H
float foo();
/*extern */float (*floatFunctionArray[3])();
#endif /* DEF_H */
//--- Def.cpp
#include "Def.h"
float foo()
{
return 0;
}
float (*floatFunctionArray[3])() =
{
foo, foo, foo
};
//--- main.cpp
#include "Def.h"
int
main(int argc, char** argv)
{
return 0;
}
Adding the commented out "extern" solves the issue.

forward declarations of structures throwing a redefinition error

This code is compiling and functioning properly on a different environment in C using gcc. I am in the process of porting it into a new C++ environment using g++ and getting a redefinition error.
I've seen similar issues, but my problem might stem from the fact that I've got predeclarations in the struct definitions and need to predeclare again in the instantiation. Here is the relevant code:
transaction.h
...
typedef int ( *pfnTrans)(transaction *);
typedef struct tag_TRANSTEP transStep; //forward declare this for the following struct.
typedef struct tag_RETURNMAP
{
int onThisReturn;
transStep * runThis;
}returnMap;
#define MAX_BRANCHES 10
struct tag_TRANSTEP
{
pfnTrans thisStepsFunction;
returnMap retMap[MAX_BRANCHES];
};
...
source.cpp
...
//Forward declaring the steps, since they reference one another.
transStep tsConsultChoreList;
transStep tsPayBills;
transStep tsMowLawn;
transStep tsFixLawnMower;
transStep tsConsultChoreList = {fnConsultChoreList, {{MOW_LAWN, &tsMowLawn},
{PAY_BILLS, &tsPayBills},
{0, NULL}}}; // this entry signifies end of returnMap
transStep tsPayBills= {fnPayBills, {{SUCCESS, &fnConsultChoreList},
{0, NULL}}}; // this entry signifies end of returnMap
transStep tsMowLawn= {fnMowLawn, {{SUCCESS, &tsConsultChoreList},
{FIX_MOWER, &tsFixLawnMower},
{0, NULL}}}; // this entry signifies end of returnMap
transStep tsFixLawnMower= {fnFixLawnMower, {{SUCCESS, &tsMowLawn},
{0, NULL}}}; // this entry signifies end of returnMap
...
I'm not getting any errors from the .h file, but for each transStep in the .cpp I am getting a "redefinition of ..." error and an accompanying "... previously declared here" error.
That's legal in C? That's not legal in C++. If you prefix the "predeclarations" with extern thusly
extern transStep tsConsultChoreList;
extern transStep tsPayBills;
// etc...
it should work. In your .h file, you are predeclaring types, not instances of types. In your .cpp file, you're declaring actual instances, telling the compiler to allocate space for them. The extern keyword tells the compiler that the variable exists, just somewhere else. Then your declarations with initialization should work fine.

Resources