member access within misaligned address 0x000000000002 for type 'struct ListNode', which requires 8 byte alignment - while-loop

How can I solve this misaligned address problem.I came across this problem when I try to solve addition of two numbers using linked list in reverse order in LeetCode
ProblemLink:https://leetcode.com/problems/add-two-numbers/
algorithm : Ive created a variable flag to check for carry over.When i tried to add the first element of linked list 1 with the first element of linked list 2 ,its throwing an error.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
struct node{
int num;
struct node *ptr;
};
struct node* create(){
struct node *ptr1=malloc(sizeof(struct node));
ptr1->ptr=NULL;
return ptr1;
}
struct node *head=NULL;
struct node *temp=NULL;
int flag=0;
while(l1!=NULL && l2!=NULL){
if(head==NULL){
head=create();
temp=head;
}
else{
temp->ptr=create();
temp=temp->ptr;
}
int a=(l1->val); //showing error
a=a+(l2->val);
a=a+flag;
int b=a%10;
flag=(a-b)/10;
temp->num=b;
l1=l1->val;
l2=l2->val;
}
while(l1==NULL && l2!=NULL){
if(head==NULL){
head=create();
temp=head;
}
else{
temp->ptr=create();
temp=temp->ptr;
}
int a=(l2->val)+flag ;
int b=a%10;
flag=(a-b)/10;
temp->num=b;
l2=l2->val;
}
while(l1!=NULL && l2==NULL){
if(head==NULL){
head=create();
temp=head;
}
else{
temp->ptr=create();
temp=temp->ptr;
}
int a=(l1->val)+flag ;
int b=a%10;
flag=(a-b)/10;
temp->num=b;
l1=l1->val;
}
while(l1==NULL && l2==NULL && flag==1){
if(head==NULL){
head=create();
temp=head;
}
else{
temp->ptr=create();
temp=temp->ptr;
}
temp->num=1;
flag=0;
}
return head;
}

Related

Initialize C++/CLI array of structures

I wish to partially initialize an array of structures like in a C++ POD type. The String^ would normally be a char* but managed C++ doesn't allow that.
#include "stdafx.h"
using namespace System;
ref struct Field
{
String^ name;
int fences;
int length;
};
int main(array<System::String ^> ^args)
{
array<Field^>^ farm =
{
{ "eenie", 10 },
{ "meenie", 20 },
{ "miny", 4 }
};
for each (Field^ field in farm)
{
field->length = field->fences * 22;
}
return 0;
}
This results in
1>arrayinit.cpp(18): error C2440: 'initializing' : cannot convert from 'const char [6]' to 'Field ^'
1> Reason: cannot convert from 'const char *' to 'Field ^'
1> No user-defined-conversion operator available, or
1> Cannot convert an unmanaged type to a managed type
So I tried
#include "stdafx.h"
using namespace System;
ref struct Field
{
String^ name;
int fences;
int length;
};
int main(array<System::String ^> ^args)
{
array<Field^>^ farm =
{
{ String("eenie"), 10 },
{ String("meenie"), 20 },
{ String("miny"), 4 }
};
for each (Field^ field in farm)
{
field->length = field->fences * 22;
}
return 0;
}
Now I get
1>arrayinit.cpp(18): error C2440: 'initializing' : cannot convert from 'System::String' to 'Field ^'
1> No user-defined-conversion operator available, or
1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
1>arrayinit.cpp(18): error C2078: too many initializers
Almost every example I've looked at only tells how to initialize an array of strings or integers. I haven't found out a way of initializing an array of structures containing strings.
Is there a simple way of doing this or do I have to create a special constructor and gcnew every element?
I found that I can gcnew every element with a special constructor. Is there a simpler way of doing this similar to a POD initialization?
#include "stdafx.h"
using namespace System;
ref struct Field
{
String^ name;
int fences;
int length;
Field(String^ x, int in_fences)
{
name = x;
fences = in_fences;
}
};
int main(array<System::String ^> ^args)
{
array<Field^>^ farm =
{
gcnew Field("eenie", 10 ),
gcnew Field("meenie", 20 ),
gcnew Field("miny", 4 )
};
for each (Field^ field in farm)
{
field->length = field->fences * 22;
}
return 0;
}
Alternatively, if Field is changed to a value instead of a reference,
#include "stdafx.h"
using namespace System;
value struct Field
{
String^ name;
int fences;
int length;
Field(String^ x, int in_fences)
{
name = x;
fences = in_fences;
}
void Init()
{
length = fences * 22;
}
};
int main(array<System::String ^> ^args)
{
array<Field>^ farm =
{
Field("eenie", 10 ),
Field("meenie", 20 ),
Field("miny", 4 )
};
for each (Field% field in farm)
{
field.Init();
}
return 0;
}
This is slightly better than gcnewing every field.

Add element to struct

I can't use ( push ) because it is used with state variable only
This is the error :
Error message
Is there any alternatives for ( push )
contract m{
struct Message{
address sender;
address receiver;
uint msgContent;
} // end struct
Message[] all;
function get ( address from ) internal
returns ( Message[] subMsgs){
for ( uint i=0; i<all.length ; i++)
{
if ( all[i].sender == from )
{
subMsgs.push (all[i]);
}
}
return subMsgs;
}
} // end contract
You can only use push on dynamic-size arrays (i.e. storage arrays), and not fixed-size arrays (i.e. memory arrays) (see Solidity array documentation for more info).
So to achieve what you want, you'll need to create a memory array with a desired size and assign each element one by one. Here is the example code:
contract m {
struct Message{
address sender;
address receiver;
uint msgContent;
} // end struct
Message[] all;
function get(address from) internal returns (Message[]) {
// Note: this might create an array that has more elements than needed
// if you want to optimize this, you'll need to loop through the `all` array
// to find out how many elements from the sender, and then construct the subMsg
// with the correct size
Message[] memory subMsgs = new Message[](all.length);
uint count = 0;
for (uint i=0; i<all.length ; i++)
{
if (all[i].sender == from)
{
subMsgs[count] = all[i];
count++;
}
}
return subMsgs;
}
} // end contract

struct entry: Manual command line access?

how does this code work: more precisely the line that passes the struct into the command line agc and argv ? what is it doing? Is there another way to do this?
#include <Foundation/Foundation.h>
int main (int argc, char * argv[]) {
struct entry dictionary[100] =
{ { "aardvark", "a burrowing African mammal" } ,
{ "abyss", "a bottomless pit' } ,
{ "acumen", "mentally sharp; keen"
{ "addle", "to become confused" } ,
{ "aerie", "a high nest" },
{ "affix","to append, attach" },
{ "agar"," a jelly made from seaweed" },
{ "ahoy"," a nautical call of greeting" },
{ "aigrette", "an ornamental cluster of feathers" } ,
{ "ajar", "partially opened" } } ;
int entries = 10;
int entryNumber;
int lookup (struct entry dictionary [], char search[],
int entries);
if ( argc != 2 ) {
NSLog (#"No word typed on the command line.");
return (1); }
entryNumber = lookup (dictionary, argv[1], entries);
if ( entryNumber != -1 )
NSLog (#"%s", dictionary[entryNumber].definition);
else
NSLog (#"Sorry, %s is not in my dictionary.", argv[1]);
return (0); }

binary search:please tell me whats wrong here

I tried binary tree data structure but found it to be not working and giving an error. Please correct my code. Thanks!
It gives warning but with the inputs in main it stops running .
#include<stdlib.h>
#include<stdio.h>
typedef struct
{
int item;
struct node * leftc;
struct node * rightc;
}node;
void create(int key, node **tree )
{
if(*tree ==0)
{
(*tree)= (node *)malloc(sizeof(node *));
(*tree)->item=key;
(*tree)->leftc=((*tree)->rightc)=NULL;
}
else
{
if(key >= (*tree)->item )
{
create(key, &((*tree)->rightc));
}
else if(key<(*tree)->item)
{
create(key, &((*tree)->leftc));
}
}
}
node * search(int key, node * tree)
{
if(tree !=NULL)
{
if(key == tree->item)
return tree;
else if(key > tree->item)
search(key, tree->rightc);
else
search(key, tree->leftc);
}
return NULL;
}
void cut(node * tree)
{
if(tree != NULL)
{
cut(tree->leftc);
cut(tree->rightc);
free(tree);
}
}
void print_preorder(node * tree)
{
if (tree) {
printf("%d\n",tree->item);
print_preorder(tree->leftc);
print_preorder(tree->rightc);
}
}
int main()
{
node * root=NULL;
create(9,&root);
create(16,&root);
create(24,&root);
create(6,&root);
return 0;
}
Change
typedef struct
{
int item;
struct node * leftc;
struct node * rightc;
}node;
to
typedef struct node
{
int item;
struct node * leftc;
struct node * rightc;
}node;
Within your structure you refer to 'struct node' so you need the name in order for it to properly reference itself. Of course, after the typedef then you can just refer to it as node.
The test program compiled and ran fine with the code given otherwise.
I know this doesn't answer your question about the error, but I noticed a major problem with your search() function. You only return the node you're looking for if it's the first one that is put into the function. The recursive calls to search() do not return anything. The function should look something like this:
node * search(int key, node * tree)
{
if (tree !=NULL)
{
if (key == tree->item) {
return tree;
} else if (key > tree->item) {
return search(key, tree->rightc);
} else if (key < tree->item) {
return search(key, tree->leftc);
}
}
return NULL;
}
Also, in your create() function, did you mean to check if (*tree == NULL) instead of if (*tree == 0)?

Is there an equivalent to __attribute__((ns_returns_retained)) for a malloc'd pointer?

I'm looking for an annotation something like
-(SomeStruct *) structFromInternals __attribute__((returns_malloced_ptr))
{
SomeStruct *ret = malloc(sizeof(SomeStruct));
//do stuff
return ret;
}
to soothe the clang static analyzer beasts.
The only viable attributes link I can find is for GCC, but it doesn't even include ns_returns_retained, which is in an extension, I assume.
EDIT:
as to why this is needed, I have a scenario that I can't repro in a simple case, so it may have to do with a c lib in an Objective-C project... The gist is, I get a static analyzer warning that the malloc in createStruct is leaked:
typedef struct{
void * data;
size_t len;
}MyStruct;
void destroyStruct(MyStruct * s)
{
if (s && s->data) {
free(s->data);
}
if (s) {
free(s);
}
}
MyStruct * createStructNoCopy(size_t len, void * data)
{
MyStruct * retStruct = malloc(sizeof(MyStruct));
retStruct->len = len;
retStruct->data = data;
return retStruct;
}
MyStruct * createStruct(size_t len, void * data)
{
char * tmpData = malloc(len);
memcpy(tmpData, data, len);
return createStructNoCopy(len, tmpData);
}
MyStruct * copyStruct(MyStruct * s)
{
return createStruct(s->len, s->data);
}
The function annotation ownership_returns(malloc) will tell the Clang static analyser that the function returns a pointer that should be passed to free() at some point (or a function with ownership_takes(malloc, ...)). For example:
void __attribute((ownership_returns(malloc))) *my_malloc(size_t);
void __attribute((ownership_takes(malloc, 1))) my_free(void *);
...
void af1() {
int *p = my_malloc(1);
return; // expected-warning{{Potential leak of memory pointed to by}}
}
void af2() {
int *p = my_malloc(1);
my_free(p);
return; // no-warning
}
(See the malloc-annotations.c test file for some more examples of their use.)
At the moment, these annotations only take effect when the alpha.unix.MallocWithAnnotations checker is run (which is not run by default). If you're using Xcode, you'll need to add -Xclang -analyzer-checker=alpha.unix.MallocWithAnnotations to your build flags.