PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label malloc. Show all posts
Showing posts with label malloc. Show all posts

Monday, November 14, 2022

[FIXED] why can't i access the pointer to a structure from another file and get the members

 November 14, 2022     c, external, malloc, static     No comments   

Issue

this a reproducible example and not the entire code the entire code is too large.. my problem was that i had a structure that i created using malloc and i needed to access it from another function in another file, but i keep getting segfault...

header file main.h

#ifndef main_a
#define main_a
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct cmd_s
{
     int n;
} cmd_t;

extern cmd_t *ptr;
void push(char *line);

#endif

the main.c file main.c

#include "main.h"
cmd_t *ptr = NULL;

int main(void)
{
    cmd_t *ptr = malloc(sizeof(cmd_t));
    ptr->n = 5;
    push("line");
    
    return (0);
}

and where i need to access the struct from named opcode.c

opcode.c

#include "main.h"

void push(char *line)
{
    int new = ptr->n;
}

note that this is not the actual code the actual code has useful values, this is an example that contains the challenge i am facing

i tried to use static instead but i got the same error. i'm still a novice in c programming.. and i don't want to change the way i created the structure, which is through malloc because another function depends on it... i just need to make that malloced structure accessible to another file in the program. thanks.


Solution

int main(void)
{
    cmd_t *ptr = malloc(sizeof(cmd_t));

You create new ptr variable visible only in function main. Your push see the global pointer ptr but not the one you have malloced.

You need to

int main(void)
{
    ptr = malloc(sizeof(*ptr));
    /* .... */

Use obiects not types in sizeof (as in this example)



Answered By - 0___________
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, November 2, 2022

[FIXED] How to read big chunk of data using fread and access them as an array in C

 November 02, 2022     c, crash, file, malloc, pointers     No comments   

Issue

I have a code with the goal of reading a binary file using fread and then processing the data and sending that to a char *buffer of size 1310720

For now (with my working code) I was reading file byte by byte for doing some processing then writing the byte 1 by 1 into an unsigned char array[i] I was using something like this

void read_input_file(FILE *stream,char *buffer)
{
    long i = 0;
    unsigned char tmp_buf[1310720] ;
    unsigned char *calc = malloc(1);
    while(i < 1310720)
    {
        fread(calc,1,1,stream);
        tmp_buf[i] = round(*calc /128);//this is an example
        i++;
    }
    
    memcpy(buffer, &tmp_buf[0], 1310720);
}

it was working but now I want (for performance reasons) to read chunk of data that are the size of the buffer. So I tried using something like this :

void read_input_file(FILE *stream,char *buffer)
{
    long i = 0;
    unsigned char tmp_buf[1310720] ;
    unsigned char *calc = malloc(1310720);

    fread(calc,1310720,1,stream);

    while(i < 1310720)
    {
        tmp_buf[i] = round(calc[i] /128);//this is an example
        i++;
    }
    
    memcpy(buffer, &tmp_buf[0], 1310720);
}

but whatever I do I got execution error where the program crash. I tried a lot of different things and code but nothing works.

So how do I read a big chunk of data into a buffer and then access it byte by byte to process the data ?


Solution

Since you say you are working on Windows, the problem is what I outlined in my comment:

The stack size limit on Windows is 1024 KiB (1 MiB) and you're trying to create a 1280 KiB buffer on the stack. Use dynamic memory allocation twice. Even on Unix-like systems, the stack size limit is typically 8 MiB, so allocating that large of an array on the stack is a little dubious.

Because your tmp_buf variable is created as a local variable on the stack, you are blowing the stack on Windows. And, as

I think your function should return a status to indicate whether it was successful or not, so I've changed the return type to int and use 0 to indicate success and -1 for failure.

That means your code needs to become more like:

enum { BUFFER_SIZE = 1310720 };

int read_input_file(FILE *stream, char *buffer)
{
    long i = 0;
    unsigned char *temp = malloc(BUFFER_SIZE);
    unsigned char *calc = malloc(BUFFER_SIZE);

    if (temp == NULL || calc == NULL)
    {
        free(temp);   // Free both in case only one was allocated
        free(calc);
        return -1;
    }

    if (fread(calc, BUFFER_SIZE, 1, stream) != 1)
    {
        free(temp);
        free(calc);
        return -1;
    }


    for (size_t i = 0; i < BUFFER_SIZE; i++)
    {
        temp[i] = round(calc[i] / 128);  //this is an example
    }
    
    memcpy(buffer, temp, BUFFER_SIZE);
    free(temp);
    free(calc);
    return 0;
}

I would be happier if the length of buffer were passed to the function for checking, but that's a decision you can make. It isn't crucial. You could also use the length argument instead of the fixed size (now in the enumerated value) to make your code more general. However, you may not need that generality at the moment.

It also isn't clear that you can't do away with temp (aka tmp_buf) by using:

calc[i] = round(calc[i] / 128.0);

Note the conversion to a floating-point constant; otherwise, there's nothing to round as the division will be an integer division. However, if the non-example calculation uses other elements of calc than just calc[i], then you do need the second array to hold the results.



Answered By - Jonathan Leffler
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, May 14, 2022

[FIXED] Why it returns me segmention fault (core dumbed)?

 May 14, 2022     c, malloc, realloc, segmentation-fault, ubuntu     No comments   

Issue

After putting two strings, it returns me segmention fault (core dumbed)

I'm running the code with gcc. Valgrind writes that there are no errors. Tried to write code that decrypts text using the Caesar method. First I enter the text to be decoded, and the second text shows how far I need to move the letters in the first text. That is, the distance is selected at which there is more correspondence in letters between the received text and the second entered text. I carefully checked everything, for me it seems that there are really no errors, or I'm just not well versed in working with memory.

Here's example

inputs

xUbbemehbT

XYlloworld

should return

Helloworld

I really don't understand why it returns me that, here is code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define INT_MSG_LEN 50;

enum {NO_ERROR = 0, 
      ERROR_INPUT = 100, 
      ERROR_LEN = 101};

static const char *error_texts[] = { "Error input!", 
                                     "Error lenght"};

void shift(char *msgEnc, char *msg, char *msgRes, char *mainMsg, char *alphabet, int offset);
void report_error(int error);
void print_error(int error);
int get_sameletters(char *msg, char *msgRes, int offset);
int get_letter(char letter, char *alphabet);
int compare(char *msgEnc, char *msg, char *msgRes, char *alphabet, int offset);
char *read_Input_Msg(int *msglen);

int main(int argc, char *argv[])
{
    int ret = NO_ERROR;
    char *msgEnc, *msg, *msgRes, *mainMsg, alphabet[53] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    int msgEncLen, msgLen;

    msgEnc = msg = msgRes = mainMsg = NULL;
    msgEncLen = msgLen = 0;

    msgEnc = read_Input_Msg(&msgEncLen);
    if (msgEnc)
        msg = read_Input_Msg(&msgLen);

    if (msgEnc == NULL || msg == NULL)
        ret = ERROR_INPUT;
    else if (msgEncLen != msgLen)
        ret = ERROR_LEN;
    
    if (ret == NO_ERROR)
        shift(msgEnc, msg, msgRes, mainMsg, alphabet, msgEncLen);
    else
        print_error(ret);

    free(msgEnc);
    free(msg);
    free(msgRes);
    free(mainMsg);
    return ret;
}

void shift(char *msgEnc, char *msg, char *msgRes, char *mainMsg, char *alphabet, int offset)
{//function for decoding text by a defined offset
    int dis;
    dis = compare(msgEnc, msg, msgRes, alphabet, offset);
    for (int i = 0; i<offset-1; ++i){
        if ((msgEnc[i] >= 'a' && msgEnc[i] <= 'z') || (msgEnc[i] >= 'A' && msgEnc[i] <= 'Z')){
            mainMsg[i] = msgEnc[i+dis];
            break;
        }
    }
    for(int i = 0; i<offset-1; ++i)
        printf("%c", mainMsg[i]);
}

void report_error(int error)
{//prints error 
    if (error >= ERROR_INPUT && error <= ERROR_LEN)
        fprintf(stderr, "%s\n", error_texts[error - ERROR_INPUT]);
}

void print_error(int error)
{//what error it is
    switch (error){
        case ERROR_INPUT:
            report_error(ERROR_INPUT);
            break;
        case ERROR_LEN:
            report_error(ERROR_LEN);
            break;
    }
}

int get_sameletters(char *msg, char *msgRes, int offset)
{//gets count of sameletters between two strings
    int sameLetters = 0;
    for (int i = 0; i<offset-1; ++i){
        if (msg[i] == msgRes[i])
            sameLetters++;
    }
    return sameLetters;
}

int get_letter(char letter, char *alphabet)
{   
    int k;
    for (int i=0; alphabet[i]; ++i){
        if (letter == alphabet[i])
            k = i;
    }
    return k;
}

int compare(char *msgEnc, char *msg, char *msgRes, char *alphabet, int offset)
{//calculate a distance between first input string and string what will get after decryption
    int distance, max = 0;
    for (int i = 0; alphabet[i]; ++i){
        for (int j = 0; msgEnc[j]; ++j){
            if ((msgEnc[i] >= 'a' && msgEnc[i] <= 'z') || (msgEnc[i] >= 'A' && msgEnc[i] <= 'Z'))
                msgRes[j] = alphabet[(get_letter(msgEnc[j], alphabet) + i) % 52];
            }
            int sameLetters = get_sameletters(msg, msgRes, offset);
            if (sameLetters > max){
                max = sameLetters;
                distance = i;
        }
    }
    return distance;
}

char *read_Input_Msg(int *msglen)
{//input messages, at the same time counts the length of the entered string
    int capacity = INT_MSG_LEN;
    char *msg = malloc(capacity);
    int c, len = 0;
    while ((c = getchar()) != EOF && c != '\n'){
        if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) {
            free(msg);
            msg = NULL;
            len = 0;
            break;
        }
        if (len == capacity){
            char *tmp = realloc(msg, capacity * 2);
            if (tmp == NULL){
                free(msg);
                msg = NULL;
                len = 0;
                break;
            }
            capacity *= 2;
            msg = tmp;
        }
        msg[len++] = c;
    }
    *msglen = len;
    return msg;
}

Solution

You fail because you call shift with msgres == null

msgEnc = msg = msgRes = mainMsg = NULL; <<<<==========
msgEncLen = msgLen = 0;

msgEnc = read_Input_Msg(&msgEncLen);
if (msgEnc)
    msg = read_Input_Msg(&msgLen);

if (msgEnc == NULL || msg == NULL)
    ret = ERROR_INPUT;
else if (msgEncLen != msgLen)
    ret = ERROR_LEN;

if (ret == NO_ERROR)
    shift(msgEnc, msg, msgRes, mainMsg, alphabet, msgEncLen);  <<<<======


Answered By - pm100
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, April 28, 2022

[FIXED] Why do I get a warning every time I use malloc?

 April 28, 2022     c, gcc, malloc, sizeof, warnings     No comments   

Issue

If I use malloc in my code:

int *x = malloc(sizeof(int));

I get this warning from gcc:

new.c:7: warning: implicit declaration of function ‘malloc’  
new.c:7: warning: incompatible implicit declaration of built-in function ‘malloc’

Solution

You need to add:

#include <stdlib.h>

This file includes the declaration for the built-in function malloc. If you don't do that, the compiler thinks you want to define your own function named malloc and it warns you because:

  1. You don't explicitly declare it and
  2. There already is a built-in function by that name which has a different signature than the one that was implicitly declared (when a function is declared implicitly, its return and argument types are assumed to be int, which isn't compatible with the built-in malloc, which takes a size_t and returns a void*).


Answered By - sepp2k
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing