Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

char array variables are destroyed after exiting from function

I use strtok() to tokenize my string in a function. After copying the values to a global char array, I print the values to ensure the functionality. Everything is OK, but when I want to access them they are destroyed.

this is the code:

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>

int client, count = 0;

volatile char *token_temp[30];
volatile int toknum = 0;

int text_test()
{
    char my_tokenised_string_buffer[255] = "Response\n\nCompany\nModel\nRevision: N01234567890\n\nOK";
    const char delimiters[3] = "\n";

    char *token = strtok(my_tokenised_string_buffer, delimiters);
    token_temp[0]= token;
    printf("first tokenised value = %s\n", token);

    while (token != NULL) {
        ++toknum;
        token = strtok(NULL, delimiters);
        token_temp[toknum]= token;
        printf("toknum : %d\t", toknum);
        printf("token id from inside tokenise loop : %s -> [%u]\n", token_temp[toknum], toknum);
    }
    printf("\n\n\n");
    for (int i = 0; i < toknum; i++) {
        printf("token [%d] value in function out of tokenise = %s\n", i, token_temp[i]);
    }
    return 0;
}

int main()
{
    text_test();
    printf("\n\n\n");

    for (int i = 0; i < toknum; i++) {
        printf("token [%d] value in main = %s\n", i, (char *)token_temp[i]);
    }
    return 0;
}

this is output enter image description here

I want to assign the values to structures but they are missed.

like image 555
momo Avatar asked Apr 18 '26 23:04

momo


1 Answers

Within the function there is declared a local array with automatic storage duration

int text_test()
{
    char my_tokenised_string_buffer[255] = "Response\n\nCompany\nModel\nRevision: N01234567890\n\nOK";
//...

that will not be alive after exiting the function.

So the array of pointers

volatile char *token_temp[30];

will contain invalid pointers and dereferencing these pointers will invoke undefined behavior.

What you need is for example to allocate dynamically a character array for each string extracted from the array my_tokenised_string_buffer.

Another approach is declare the array my_tokenised_string_buffer as having static storage duration specifying the keyword static

static char my_tokenised_string_buffer[255] = "Response\n\nCompany\nModel\nRevision: N01234567890\n\nOK";
like image 93
Vlad from Moscow Avatar answered Apr 20 '26 12:04

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!