Whole Structure is being replaced with the last pointer Value - structure

In my program I have used an array of pointers as a structure variable to get first name and second name from the user.
The following is my function call statement:
ret_val = update_person(&ptr_person[person_index],f_name,s_name);
where ptr_person[SIZE] is a pointer variable and f_name and s_name are character array variables.
The following is my function definition where name_ret is int:
name_ret update_person(person_name_et **person,char *first_arg,char *second_arg)
{
int val = SUCCESS, val1 = SUCCESS,val2= SUCCESS;
int f_len = sizeof(first_arg);
int s_len = sizeof(second_arg);
val2 = remove_newline(first_arg);
val1 = remove_newline(second_arg);
val = allocate_person(person, f_len, s_len);
if((val && val1) == SUCCESS)
{
(*person)->first_name = first_arg;
(*person)->second_name = second_arg;
return SUCCESS;
}
else
{
return FAILURE;
}
}
The problem in the code is it works fine at the instance but when the function is called next iteration the ptr_Person[0] is replaced with ptr_person[1] and if we have 5 instances then all the 5 variables are replaced by the last values.

Related

tried check valid palindrom string problem solving using kotlin but there is one of the testcase is not passed i tried several times

this is the problem
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s, return true if it is a palindrome, or false otherwise.
Example 1:
Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
Example 2:
Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.
myCode
class Solution {
fun isPalindrome(s:String):Boolean {
var s1 = s.toLowerCase()
var myStringBuilder = StringBuilder()
var n = s1.length-1
var n1=myStringBuilder.length
for ( i in 0..n) {
if (Character.isLetterOrDigit(s1[i])) {
myStringBuilder.append(s1[i])
}
}
for( i in 0 .. (n1/2)-1){
if(myStringBuilder[i] != myStringBuilder[n1-i-1]){
return false
}
}
return true
}
}
the first case passed
but this is not passed as per the result Input: s = "race a car result true expected is false
You're initialising n1 too early:
// create an -empty- StringBuilder
var myStringBuilder = StringBuilder()
...
// since it's empty, n1 == 0
var n1=myStringBuilder.length
You're setting it to the length of the StringBuilder contents before you've actually put anything in it. This is a simple value you're setting, it's not a reference to the length getter that will give the current value when you access it. You set it once and that's its value forever.
So your last loop, the one that checks if it's a palindrome or not, never actually runs:
// since n1 is 0, this is for (i in 0..0)
for( i in 0 .. (n1/2)-1){
You can fix it by initialising n1 when you've finished adding your content to the StringBuilder, so you can get its final length:
for ( i in 0..n) {
if (Character.isLetterOrDigit(s1[i])) {
myStringBuilder.append(s1[i])
}
}
// StringBuilder is complete, grab its final length
var n1 = myStringBuilder.length
// now you can use it
for (i in 0..(n1/2)-1) {
Just fyi, there's also an until operator that works like .. except it doesn't include the last value of the range. So you can write
for (i in 0 until (n1/2))
if you want!
You can use this simple solution.
fun isPalindrome(s:String):Boolean {
val str = s.filter { it.isLetterOrDigit() }.lowercase()
for (i in 0..str.length/2 ){
if (str[i]!=str[str.length-i-1])
return false
}
return true
}
Edit:
By the #cactustictacs comment, you can do this in much more simple way.
fun isPalindrome(s:String):Boolean {
val str = s.filter { it.isLetterOrDigit() }.lowercase()
return str == str.reversed()
}

"attempt to call table" without for

When I call the method stream that I made, with any table as argument, I get the error "attempt to call table".
As far as I know this error only occurs when I use a for wrong, but I don't have a for in the code that is executed...
function stream(input)
...
local function _stream(input)
local result = {
_stream = true,
_data = input._data or input,
-- Without the Operation-wrapping no function could access the input
-- Intermediate Operations
concat = function(str) return _concat(input,str) end,
distinct = function(func) return _distinct(input,func) end,
filter = function(func) return _filter(input,func) end,
limit = function(n) return _limit(input,n) end,
map = function(func) return _map(input,func) end,
skip = function(n) return _skip(input,n) end,
sort = function(func) return _sort(input,func) end,
split = function(func) return _split(input,func) end,
-- Terminal Operations
allmatch = function(func) return _allmatch(input,func) end,
anymatch = function(func) return _anymatch(input,func) end,
collect = function(coll) return _collect(input,coll) end,
count = function() return _count(input) end,
foreach = function(func) return _foreach(input,func) end,
max = function(func) return _max(input,func) end,
min = function(func) return _min(input,func) end,
nonematch = function(func) return _nonematch(input,func) end,
reduce = function(init,op) return _reduce(input,init,op) end,
toArray = function() return _toArray(input) end
}
return result
end
if input == nil then
error("input must be of type table, but was nil")
elseif type(input) ~= "table" then
error("input must be of type table, but was a "..type(input)..": "..input)
end
return _stream(input)
end
table.stream = stream
Full Source - Older Version (where the argument gets deleted for some reason)
I want to use the method for a more stream-based programming style.
Very similar to this project, but more not only for numbers and with named keys.
In your code
function stream(input)
-- ...
local function _count()
local count = 0
for k, v in pairs(input._data) do
count = count + 1
end
return count
end
-- ...
local function _stream(input)
local result = {
_stream = true,
_data = input._data or input,
-- ...
count = _count,
-- ...
}
return result
end
return _stream(input)
end
print(stream({1,2,3}).count())
the created object _stream(input) does contain _data field, but input upvalue still refers to your argument {1,2,3} which doesn't have _data field.
It could be fixed by working with the object instead of input argument:
function stream(input)
-- ...
local obj
local function _count()
local count = 0
for k, v in pairs(obj._data) do
count = count + 1
end
return count
end
-- ...
local function _stream(input)
local result = {
_stream = true,
_data = input._data or input,
-- ...
count = _count,
-- ...
}
return result
end
obj = _stream(input)
return obj
end
print(stream({1,2,3}).count())

Unstable Postgresql C Function

I'm running PG 9.5 on Win 10 64-bit. I'm compiling C under VS 2016.
I am forming a function that will evolve into a somewhat complex beast. To test out my initial efforts, the function accepts an array of int4 (this works fine and the code for processing it is not shown here). The function then grabs a few rows from a table, pushes the values into a FIFO, then pulls them out and renders the results. This approach is strategic to how the function will operate when complete.
The function works fine on first call, then throws this on any further calls:
ERROR: cache lookup failed for type 0 SQL state: XX000
I have no idea what is causing this.
However, sometimes it doesn't throw an error but executes without end.
Here is my code as lean as I can get it for question purposes:
PG:
CREATE TABLE md_key
(
id serial NOT NULL PRIMARY KEY,
pid int4 NOT NULL,
key integer NOT NULL,
vals int4[]
);
…
CREATE OR REPLACE FUNCTION md_key_query(int4[])
RETURNS TABLE (
id int4,
vals int4[]) AS E'\RoctPG', --abreviated for question
'md_key_query'
LANGUAGE c IMMUTABLE STRICT;
…
select * from md_key_query(array[1,2,3,4]::int4[])
C:
PG_FUNCTION_INFO_V1(md_key_query);
typedef struct
{
Datum id;
Datum vals;
} MdKeyNode;
typedef struct fifoAry
{
MdKeyNode nodes[32];
struct fifoAry *next;
int32 readpos;
int32 writepos;
} FifoAry;
typedef struct
{
FifoAry *fifo;
FifoAry *tail;
FifoAry *head;
uint32 nodescount;
Datum *retvals[2];
bool *retnulls[2];
} CtxArgs;
inline void push(CtxArgs *args, Datum id, Datum vals)
{
if (args->head->writepos == 32)
args->head = args->head->next = (FifoAry*)palloc0(sizeof(FifoAry));
MdKeyNode *node = &(args->head->nodes[args->head->writepos++]);
node->id = id;
node->vals = vals;
args->nodescount++;
}
inline MdKeyNode* pop(CtxArgs *args)
{
// if (!args->nodescount)
// return NULL;
if (args->tail->readpos == 32)
args->tail = args->tail->next;
args->nodescount--;
return &(args->tail->nodes[args->tail->readpos++]);
}
// use STRICT in the caller wrapper to ensure a null isn't passed in
PGMODULEEXPORT Datum md_key_query(PG_FUNCTION_ARGS)
{
uint32 i;
FuncCallContext *funcctx;
HeapTuple tuple;
MdKeyNode *node;
CtxArgs *args;
if (SRF_IS_FIRSTCALL())
{
funcctx = SRF_FIRSTCALL_INIT();
MemoryContext oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
ArrayType *a = PG_GETARG_ARRAYTYPE_P(0);
Datum *in_datums;
bool *in_nulls;
bool fieldNull;
SPITupleTable *tuptable = SPI_tuptable;
int32 ret;
uint32 proc;
if (get_call_result_type(fcinfo, NULL, &funcctx->tuple_desc) != TYPEFUNC_COMPOSITE)
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("function returning record called in context that cannot accept type record")));
deconstruct_array(a, INT4OID, 4, true, 'i', &in_datums, &in_nulls, &ret);
if (!ret)
PG_RETURN_NULL();
(SPI_connect();
// initialize and set the cross-call structure
funcctx->user_fctx = args = (CtxArgs*)palloc0(sizeof(CtxArgs));
args->fifo = args->tail = args->head = (FifoAry*)palloc0(sizeof(FifoAry));
args->retvals = (Datum*)palloc(sizeof(Datum) * 2);
args->retnulls = (bool*)palloc0(sizeof(bool) * 2);
BlessTupleDesc(funcctx->tuple_desc);
// do some work here
// this is simply a test to see if this function is behaving as expected
ret = SPI_execute("select id, vals from public.md_key where vals is not null limit 64", true, 0);
if (ret <= 0)
ereport(ERROR, (errcode(ERRCODE_SQL_ROUTINE_EXCEPTION), errmsg("could not execute SQL")));
proc = SPI_processed;
if (proc > 0)
{
TupleDesc tupdesc = SPI_tuptable->tupdesc;
SPITupleTable *tuptable = SPI_tuptable;
for (i = 0; i < proc; i++)
{
tuple = tuptable->vals[i];
push(args, SPI_getbinval(tuple, tupdesc, 1, &fieldNull), SPI_getbinval(tuple, tupdesc, 2, &fieldNull));
}
}
SPI_finish();
MemoryContextSwitchTo(oldcontext);
}
funcctx = SRF_PERCALL_SETUP();
args = funcctx->user_fctx;
if (args->nodescount > 0)
{
node = pop(args);
args->retvals[0] = node->id;
args->retvals[1] = node->vals;
tuple = heap_form_tuple(funcctx->tuple_desc, args->retvals, args->retnulls);
SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple));
}
else
{
SRF_RETURN_DONE(funcctx);
}
}
Fixed it. Moved one command as shown here:
{
// function is unstable if this is put earlier
SPI_finish();
SRF_RETURN_DONE(funcctx);
}

junit test case with null object

I want to write Person class with 3 parameter constructor and if user give null string for name and surname for a person, I want to return null for that object because I want to use junit assertNull function to show that object is not created with null string.
public Person(String names,String surnames,int ages)
{
if(!names.equals(null) && !surnames.equals(null))
{
name = names;
surname = surnames;
}
else
{
return;
}
if(ages > 0)
age = ages;
else
return;
}
and test is like that
#Test
public void createPerson()
{
String ad = null;
String soyad = null;
int age = 10;
Person p = new Person(ad, soyad, age);
assertNull("Object is not created!", p );
}
how can do it I get null pointer exception?
You get a NullPointerException because you are calling the equals method on a null object. If you want to check whether a String is not null, you need to use someString != null.
What you need to do is:
if (names != null && surnames != null)
But that does not solve your problem that it is not possible to return null from a constructor. The only thing you could do ist to throw a NullPointerException—and that is exactly what your code does. There must be some other way to solve the problem you have.

Get varient array from VC++ dll to vb.net application

I have to get the Features array in vb.net application. How this can be done. This is a function in VC++ .
STDMETHODIMP CclsLicense::FeatureList(VARIANT* Features,BSTR HostName, VARIANT_BOOL *ret){
USES_CONVERSION;
int status = 0;
int iCount = 0;
int nLicenseFeatures = 0;
char **featureList = NULL; // List of features
// Safe Array
SAFEARRAYBOUND bound[1];
SAFEARRAY *safeArray = NULL; // A Safe array for VB
CComVariant *pBstr = NULL; // Array of BSTR Value
// Initialize the return value
*ret = VARIANT_FALSE;
nLicenseFeatures = 0;
featureList = new char*[MAX_FEATURES];
for (i=0;i<4;i++)
{
featureList[nLicenseFeatures]=array[i];
nLicenseFeatures++;
}
// Array starts at 0 and has the number of features as elements
bound[0].lLbound = 0;
bound[0].cElements = nLicenseFeatures;
// Initialize Array
if((safeArray = ::SafeArrayCreate( VT_VARIANT, 1, bound)) == NULL)
return E_FAIL;
::VariantClear(Features);
Features->vt = VT_VARIANT | VT_ARRAY;
Features->parray = safeArray;
//use direct access to data
if(FAILED(hr = ::SafeArrayAccessData(safeArray, (void HUGEP**)&pBstr)) || pBstr == NULL)
return hr;
iCount = 0;
while( featureList[iCount] != NULL )
{
// Add to Array
if(pBstr[iCount].bstrVal != NULL)
{
::SysFreeString(pBstr[iCount].bstrVal);
pBstr[iCount].bstrVal = NULL;
}
if(featureList[iCount] == NULL)
pBstr[iCount].bstrVal = ::SysAllocString(OLESTR("")); //imposible
else
pBstr[iCount].bstrVal = ::SysAllocString(T2OLE(featureList[iCount]));
pBstr[iCount].vt = VT_BSTR;
// Increment counter
iCount++;
}
// Release Array
::SafeArrayUnaccessData(safeArray);
*ret = VARIANT_TRUE;
return S_OK;
}
Vb.Net function to get the list of features
Public Shared Function FeatureList(ByVal strLicensePath As String)
Dim features(10) As String
Try
m_objUTSLicense = CreateObject("dll name")
Call m_objUTSLicense.FeatureList(features, "192.168.1.3")
Catch ex As Exception
End Try
Dim i As Integer
Dim size As Integer = features.Length
For i = 0 To size - 1
MessageBox.Show(features(i))
Next
End Function
When i am trying this code, getting the error "Attempted to read or write protected memory. This is often an indication that other memory is corrupt"
I can't test this without your whole project, but you might try declaring a member variable (rather than a local) so that you can apply the necessary marshalling attribute. Something like:
Imports System.Runtime.InteropServices
<MarshalAs(UnmanagedType.SafeArray, safearraysubtype:=VarEnum.VT_BSTR)>
Private features As System.Array