值未使用而被初始化

时间:2019-01-18 17:52:04

标签: c

在我的代码中,我使用malloc为我的项目创建n个字符串 然后,我创建了'tr'来放置来自 ** str小写字母。 它给我一个错误:

  
    

运行时检查失败#3-变量'str'未被使用而被初始化。

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

void main(void)
{
    int n;
    char **str;
    char *tr;
    int cnt, k;
    cnt = k = NULL;
    printf("Enter number fo strings:\n");
    scanf("%d", &n);
    for (int i = 0; i < n; i++)
        str[i] = (char*)malloc(sizeof(char)*n);

    str = (char**)malloc(sizeof(char)*n + 1);

    puts("Enter The strings");
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; i < n; j++)
            scanf("%s", &str[i][j]);
    }
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; i < n; j++)
        {
            if (str[i][j] >= 'a' && str[i][j] <= 'z')
                cnt++;
        }
    }

    tr = (char*)malloc(sizeof(char)*(cnt + 1));
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; i < n; j++)
        {
            if (str[i][j] >= 'a' && str[i][j] <= 'z')
                tr[k++] = str[i][j];
        }
    }

    tr[k] = NULL;
    puts(tr);
    free(tr);
    free(str);
}

3 个答案:

答案 0 :(得分:3)

char

您使用未初始化的char **str; char *tr; int cnt, k; cnt = k = NULL; printf("Enter number fo strings:\n"); scanf("%d", &n); for (int i = 0; i < n; i++) str[i] = (char*)malloc(sizeof(char)*n); // here 。你能指望什么? str的值不确定,因为它尚未初始化,并且几乎可以肯定包含无效的指针值。取消引用无效的指针(操作符str会取消引用)是未定义的行为。

您要做的是首先为[]分配内存,以保存指向字符串的指针。

顺便说一句。

str

也是不正确的。不需要内部循环从stdin读取输入并将其存储在puts("Enter The strings"); for (int i = 0; i < n; i++) { for (int j = 0; i < n; j++) scanf("%s", &str[i][j]); } 中。另外,请勿在未指定with的情况下使用str[i]来限制写入目的地的字符数。

%s

这就是if (str[i][j] >= 'a' && str[i][j] <= 'z') 中的islower()的目的。

<ctype>

这还不足以释放内存,因为free(str); 指向许多指向str的指针,这些指针也指向已分配的内存。

char

营救。

答案 1 :(得分:1)

您的这两部分代码顺序错误:

def make_move(path):
    image_folder = path
    video_name = 'video.avi'
    images = [img for img in os.listdir(image_folder) if img.endswith(".jpeg")]
    frame = cv2.imread(image_folder + images[0], cv2.IMREAD_COLOR)

    print(os.path.isfile(image_folder + images[0]))# True
    print(frame) # prints None
    height, width, layers = frame.shape # Error here


    video = cv2.VideoWriter(video_name, 0, 1, (width,height))

    for image in images:
         video.write(cv2.imread(os.path.join(image_folder, image)))

    cv2.destroyAllWindows()
    video.release()

您需要先为for (int i = 0; i < n; i++) str[i] = (char*)malloc(sizeof(char)*n); str = (char**)malloc(sizeof(char)*n + 1); 分配内存,然后才能分配给str。它应该是str[i];无需为此添加1(您只需要在sizeof(char *) * n中添加1,因为您在末尾添加了一个空终止符)。

应该是:

tr

之后

另外,请阅读Do I cast the result of malloc?Why is it considered a bad practice to omit curly braces?

答案 2 :(得分:1)

您在使用前未分配,正在使用 then 分配,但是分配不正确。正确的分配是:

import fetch from 'isomorphic-fetch';

export function saveData(rec) {
  debugger
  return function(dispatch){
    return fetch(`/api/v1/charts`, {
      credentials: "include",
      method: "POST",
      headers: {
        'Accept': "application/json",
        'Content-Type': "application/json",
      },
      body: JSON.stringify(rec)
    })
    .then(res => {
      return res.json()
    }).then(data => {
         debugger
         dispatch({type: 'ADD_CHART', payload: data})
    })
  }
}

module Api::V1
  class ChartsController < ApplicationController

      def index
          @charts = Chart.all
          render json: @charts, include: ["people", "weights"]
      end

      def create
          binding.pry
          @chart = Chart.create(chart_params)
          render json: @chart, include: ["people", "weights"]
      end

      def destroy
          Chart.find(params[:id]).destroy
      end

      private

      def chart_params
          params.require(:chart).permit(:id, :date, people_attributes: [:name, weights_attributes: [:pounds, :currentDate] ])
      end
  end
end

module Api::V1
  class PersonsController < ApplicationController

    def index
      @persons = Person.all
      render json: @persons, include: "weights"
    end

    def create
        binding.pry
        @person = Person.create(person_params)
        render json: @person, include: "weights"
    end

    private

    def person_params
      params.require(:person).permit(:id, :name, weights_attributes: [:pounds, :currentDate])
    end
  end
end

module Api::V1
  class WeightsController < ApplicationController

      def index
         @weights = Weight.all
         render json: @weights
      end

      def create
         binding.pry
         e = Weight.where(:person_id => params[:person_id], :currentDate => params[:currentDate])
          if !e.empty?
            e.first.pounds = params[:pounds]
            e.first.save!
            @weight = e
          else
            @weight = Weight.create(weight_params)
          end

          render json: @weight
      end

      private

      def weight_params
        params.require(:weight).permit(:id, :pounds, :currentDate, :person_id)
      end
  end
end

class ApplicationController < ActionController::API
end

str = malloc(sizeof(char*) * n); str的数组,不是char*的数组。

倾听编译器警告是件好事,但是这一警告确实很具体,您应该能够找到问题所在。分配的顺序非常重要,“足够接近”是不可接受的。它要么起作用,要么是不确定的行为。