memcpy extra starting characters [closed] - c

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I'm having some trouble using memcpy in that when the memcpy operation is performed I get:
"ÍÍWF03-021913.datýýýý««««««««þ"
when I should get:
"WF03-021913.datýýýý««««««««þ"
I don't know where these leading "ÍÍ" are coming from.
Code:
note: lpszFileName = "WF03-021913.dat"
typedef struct {
BYTE cbRequestType;
BYTE cbFileName;
char* szFileName;
} UFTP_GET_FILE_INFO_REQUEST;
BOOL Uftp_BuildFileInfoRequest(PUFTP_REQUEST request, LPCTSTR lpszFileName)
{
UFTP_GET_FILE_INFO_REQUEST *fileInfo;
int fileNameLen;
if (lpszFileName == NULL) {
ASSERT( 0 );
return FALSE;
}
fileNameLen = strlen( lpszFileName );
if (fileNameLen == 0)
return FALSE;
request->dwRequestSize = sizeof(UFTP_GET_FILE_INFO_REQUEST) -
sizeof(void*) + fileNameLen;
request->RequestBuffer = malloc( request->dwRequestSize );
if ( !request->RequestBuffer ) {
TRACE0("Failed to allocate RequestBuffer");
return FALSE;
}
fileInfo = (UFTP_GET_FILE_INFO_REQUEST*) request->RequestBuffer;
fileInfo->cbRequestType = UFTP_GET_FILE_INFO;
fileInfo->cbFileName = fileNameLen;
memcpy(&fileInfo->szFileName, lpszFileName, fileNameLen);
return TRUE;
}

I'm only guessing here, but my guess is that fileInfo->szFileName is a pointer. This means that &fileInfo->szFileName is a pointer to a pointer, so you copy to a complete other area of memory.
Also, you don't copy the terminating '\0' character needed. You need fileNameLen + 1 for that, both when allocating and when copying.
If you really want it all in contiguous memory, you should probably change the structure to end with a character-array of size zero (may not be supported by your compiler, then use an array of size 1) and use sizeof(UFTP_GET_FILE_INFO_REQUEST) + fileNameLen + 1 as the size to allocate. Then you can use the array as a normal string array.
And if you fix those problems, you have yet another problem: You don't initialize the pointer to point to allocated memory. This means it will point to some random memory.
All of these errors will lead to undefined behavior, and I would say you are lucky it didn't crash.

Related

Dynamically reallocating an array of structs in C [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
A part of my code will read in an unknown number of lines from a text file, parse that line into a structure (tempSomeStruct), resize the SomeStruct_Array, and then add that tempSomeStruct into the newly opened spot in memory.
However after a few times through the while loop, my program stops and says
myApplication.exe has triggered a breakpoint.
I did not set a breakpoint, and doing some digging, it LOOKS like the breakpoint is due to heap corruption from my call to realloc. I am pretty new to dynamic allocation, so while I have searched and found a few possible causes, so far no fixes have worked.
How am I corrupting the heap in this situation, and what do I do differently to avoid doing so?
I have a function like this:
int growArray(SomeStruct **SomeStruct_Array,int currentSize, int numNewElements)
{
const int totalSize = currentSize + numNewElements;
SomeStruct *temp = (SomeStruct*)realloc(*SomeStruct_Array,(totalSize * sizeof(SomeStruct)));
if (temp == NULL)
{
printf("Cannot allocate more memory.\n");
return 0;
}
else
{
*SomeStruct_Array = temp;
}
return totalSize;
}
and it is called in elsewhere like this:
SomeStruct* SomeStruct_Array = (SomeStruct *) calloc(1,sizeof(SomeStruct));
int Error_Array_Size = 0;
if(SomeStruct_Array == NULL)
{
printf("Cannot allocate initial memory for data\n");
return;
}
while(fgets(line,sizeof(line), file) != NULL)
{
parseTextIntoSomeStruct(line, &tempSomeStruct);
SomeStruct_Array_Size = growArray(&SomeStruct_Array,SomeStruct_Array_Size,1);
if(SomeStruct_Array_Size > 0)
{
SomeStruct_Array[SomeStruct_Array_Size] = tempSomeStruct;
}
}
Your new array's size is SomeStruct_Array_Size, and you immediately write to SomeStruct_Array[SomeStruct_Array_Size] which is one past the end of the array! Remember, C arrays are zero-indexed.
Use
SomeStruct_Array[SomeStruct_Array_Size-1] = tempSomeStruct;
instead.

Array of files and value assigning [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have 2 questions.
I want to create an array of files in C. But I'm not sure whether I have to malloc the size before or not.Can I just use FILE** files as an array or do I have to malloc them before. And if I have to make space, do I need to reserve 4 bytes (x86)?
I have the variable "char extra[8] = { 0xAE00AF00B000B100 };" and I want to assign it to the end of another char array[24]. Is there a faster way of doing that without having to type in every value by hand or using a for loop.
char extra[8] = { 0xAE00AF00B000B100 };
// index is a random place in the string
name[index] = '\0';
i = 0;
if (index > 16) {
for (i = 24-index; i < 8; i++) {
index++;
name[index] = extra[i];
}
}
else {
name[17] = 0xAE;
name[18] = 0x00;
name[19] = 0xAF;
name[20] = 0x00;
name[21] = 0xB0;
name[22] = 0x00;
name[23] = 0xB1;
name[24] = 0x00;
}
I need to add those extra bytes btw.
I want to create an array of files in C. But I'm not sure whether I
have to malloc the size before or not.Can I just use FILE** files as
an array or do I have to malloc them before. And if I have to make
space, do I need to reserve 4 bytes (x86)?
If you need to have an array of files, it is possible to use an array of pointers as follow:
#include <stdio.h>
FILE *array[NB_FILES];
Or you can do it dynamically if NB_FILES is only known at runtime.
#include <stdio.h>
#include <stdlib.h>
FILE **array = malloc(nb_files * sizeof *array);
I have the variable "char extra[8] = { 0xAE00AF00B000B100 };" and I want to assign it to the end of another char array[24]. Is there a faster way of doing that without having to type in every value by hand or using a for loop.
The standard C library provides the function memcpy, which is a builtin on many compiler (so it will be faster than a for loop).
#include <string.h>
char array[24];
char extra[8];
memcpy(array + sizeof array - sizeof extra - 1, extra, sizeof extra);

Creating 2D struct [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have aproblem with this code, it compiles ok. But it crashes imidiately after memory could not be written error.
Debugger says the problem is in the line *grid = (grid_t**)malloc(sizeof(grid_t)*GRID_HEIGHT); , i must be missing something obvious.
I'm trying to create a pointer to a 2D struct.
#define GRID_WIDTH 12
#define GRID_HEIGHT 22
typedef struct
{
int piece;
int edge;
}grid_t;
grid_t*** grid;
*grid = (grid_t**)malloc(sizeof(grid_t)*GRID_HEIGHT);
for(int i = 0 ; i < GRID_HEIGHT ; i++)
{
*grid[i] = (grid_t*)malloc(sizeof(grid_t)*GRID_WIDTH);
}
You dereference an unallocated pointer:
grid_t*** grid;
*grid = (grid_t**)malloc(sizeof(grid_t)*GRID_HEIGHT);
grid is not allocated when you do *grid, so it's undefined behavior.
If you want to dynamically allocate two-dimensional structs, you first need to allocate enough memory for pointers (grid_t*) in the first level:
grid_t** grid;
grid = malloc(sizeof(*grid) * GRID_HEIGHT);
Then you can allocate each element with a loop:
for(int i = 0 ; i < GRID_HEIGHT ; i++)
{
grid[i] = malloc(sizeof(**grid) * GRID_WIDTH);
// ...then you can do grid[i]->piece = 42; etc..
}
Now, from what I can see, you probably don't even need dynamic allocation. If you don't need malloc, don't use it, just use good ol' arrays instead:
grid_t grid[GRID_HEIGHT][GRID_WIDTH];

(C) realloc array modifies data _pointed_ by items [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
(C) realloc array modifies data pointed by items
Hello,
A nice weird bug I feel like sharing ;-) Requires some preliminary explanations:
First, I have a type of strings PString which hold their size (and a hash value), followed by a flexible array member with the bytes. Here is the type and kind of constructor (the printfl statement at the end is debug):
typedef struct {
size_t size;
uint hash;
char bytes[];
} PString;
// offset from start of pstring struct to start of data bytes:
static const size_t PSTRING_OFFSET = sizeof(size_t) + sizeof(uint);
PString * pstring_struct (string str, size_t size, uint hash) {
// memory zone
char *mem = malloc(PSTRING_OFFSET + size * sizeof(char));
check_mem(mem);
// string data bytes:
memcpy(mem + PSTRING_OFFSET, str, size);
mem[PSTRING_OFFSET + size] = NUL;
// pstring struct:
PString * pstr = (PString *) mem;
pstr->size = size;
pstr->hash = hash;
printfl("*** str:'%s' (%u) --> pstr:'%s' (%u) 0x%X",
str, size, pstr->bytes, pstr->size, pstr); ///////////////////////
return pstr;
}
[Any comment on this construction welcome: I'm not sure at all to do things right, here. It's the first time I use flexible array members, and I could not find exemples of using them in allocated structs.]
Second, those pstrings are stored in a string pool, meaning a set implemented as hash table. As usual, "buckets" for collisions (after hash & modulo) are plain linked lists of cells, each holding a pstring pointer and a pointer to next cell. The only special detail is that the cells themselves are stored in an array, instead of beeing allocated anywhere on the heap [1]. Hope the picture is clear. Here is the definition of Cell:
typedef struct SCell {
PString * pstr;
struct SCell * next;
} Cell;
All seemed to work fine, including a battery of tests of the pool itself. Now, when testing a pstring routine (search), I noticed a string changed. After some research, I finally guessed the problem is related to pool growing, and endly could reduce the issue exactly around the growing of the array of cells (so, well before redistributing cells into lists). Here is the lines of debug prints around this growing, with copy of the show_pool routine producing the output (just shows the strings), and the output itself:
static void pool_grow (StringPool * pool, uint n_new) {
...
// Grow arrays:
show_pool(pool); /////////////////////
pool->cells = realloc(pool->cells, pool->n_cells * sizeof(Cell));
check_mem(pool->cells);
show_pool(pool); ////////////////////
...
static void show_pool (StringPool * pool) {
if (pool->n == 0) {
printfl("{}");
return;
}
printf("pool : {\"%s\"", pool->cells[0].pstr->bytes);
PString * pstr;
uint i;
for (i = 1; i < pool->n; i++) {
pstr = pool->cells[i].pstr;
printf(", \"%s\"", pstr->bytes);
}
printl("}");
}
// output:
pool : {"", "abc", "b", "abcXXXabcXXX"}
pool : {"", "abc", "b", "abcXXXabcXXXI"}
As you can see, the last string stored has an additional byte 'I'. Since in the meanwhile I'm just calling realloc, I find myself a bit blocked for further debugging; and thinking hard does not help in throwing light on this mystery. (Note that cells just hold pstring pointers, so how can growing the array of cells alter the string bytes?) Also, I'm bluffed by the fact there seems to be a quite convenient NUL just after the mysterious 'I', since printf halts there.
Thank you.
Can you help?
[1] There is no special reason for doing that here, with a string pool. I usually do that to get for free an ordered set or map, and in addition locality of reference. (The only overhead is that the array of cells must grow in addition to the array of buckets, but one can reduce the number of growings by predimensioning.)
Since size doesn't include the null terminator,
mem[PSTRING_OFFSET + size] = NUL;
is invalid. Every other issue stems from this.

how check null pointer in c programming , get this compile error: used struct type value where scalar is required , [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
struct s_client *cur_client(void){
return (struct s_client *) pthread_getspecific(getclient);
}
int32_t chk_process (int32_t) {
...
struct s_client *ptr = cur_client();
//FIXME
// how could i check in this line , just when the value of
// ptr is not zero , then it goes to it's next line?`
send_data (ptr, index);
...
...
}
i would like to check , only at the time that the value of ptr , is not zero , it goes to it's next line , i tried this line of code
if (*ptr != 0)
but as expected this wasn't correct , since it's not check the value !
Edit2 :
Well , i found myself the reason , since ptr fullfilled from pthread_getspecific . If pthread_getspecific is called on the key whose thread specific data is being destroyed, the value NULL is returned. For more info , u could check the man page ... End of the story
Edit1 :
Well This is the struct name cur_client() , which is use in above codes
You probably wanted to test if the pointer was not null. If so, you shouldn't dereference it when making the comparison:
if (ptr != 0)
Or:
if (ptr != NULL)
ptr is a pointer to struct s_client, whereas *ptr is the struct s_client itself.
You're not comparing the pointer to 0, you're trying to compare the structure to 0, which can't be done.
It seems that you want to check whether the struct that is pointed to by the pointer contains zeroes only. You can do it like this:
int i, isNonzero = 0;
for (i = 0; i < sizeof(*ptr); i++) {
if (((char *)ptr)[i] != 0) {
isNonzero = 1;
break;
}
}
if (isNonzero) {
/* etc. */
}
Edit: no, ptr is not the address of the pointer, it's the pointer itself. Compare it to NULL if you want to check that. A pointer is just a normal variable itself that holds an integer representing a memory address. A pointer-typed variable (which ptr is) has an address itself, which it seems you think gets compared when you use the != operator. No, it doesn't - you would have to write
if (&ptr != NULL) {
}
for doing that. Don't worry, other answers' suggestions are also good.
And please, make the effort to read a tutorial on C pointers. This is something too basic to be asked on StackOverflow.

Resources