为什么我的函数不返回空指针?

问题描述 投票:0回答:1

我在视觉代码方面有问题,在联机编译器上一切正常,但是在stm32 nucleo上尝试时,它没有返回NULL,这是哪里出了问题?它不能中断while循环。

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

int funk(char *skai) {
    char delim[] = "+-=";
    int i = 0;
    float x, d = 0;
    char *array[2];
    char *ptr = strtok(skai, delim);
    while (ptr != NULL) {
        array[i++] = ptr;
        ptr = strtok(NULL, delim); // <---- doesnt return null, endless loop
    }
    int a = atoi(array[0]);
    float b = atof(array[1]);
    int c = atoi(array[2]);
    if (c != 0) {
        d = b * b - 4 * a * c;
        if (d > 0) {
            float root1 = (-b + sqrt(d)) / (2 * a);
            float root2 = (-b - sqrt(d)) / (2 * a);
            if (root1 > root2) {
                x = root1;
            } else {
                x = root2;
            }
        } else {
            x = -b / (2 * a);
        }
    } else {
        x = b / a;
    } //printf("%0.3f\n", x);
    return x;
}

int main(void) {
    char rxd[20] = "2x^2+x/5+2=0";
    funk(rxd);
}
c parsing pointers stm32 strtok
1个回答
2
投票

给定skai指向包含“ 2x + 2 = 0”的char数组,使用定界符“ +-=”对strtok的调用序列应首先返回指向(第一个字符的“ 2x”,然后是“ 2”,然后是“ 0”,然后是空指针。编写的代码尝试将这些值存储在array[0]array[1]array[2]中。但是,array没有元素2,因为它仅由两个元素定义。因此,程序使数组溢出,并且程序的结果行为未由C标准定义。可能是程序然后以导致strtok异常的方式覆盖内存。

array的定义更改为更大,然后在调用strtok的循环内,监视i的值:如果达到数组大小的限制,则打印错误消息并终止函数(或整个程序)。


0
投票

您的问题之一在这里:

 char *array[2];

它不必是一个指针,它需要更多空间:

 char array[3];

仅此一项将允许while循环退出

© www.soinside.com 2019 - 2024. All rights reserved.