为什么我的程序会出现段错误?

[ad_1]

我正在使用 SDL 2.23.6 和 gcc 12.3。 当我编译和链接时,我只收到一些警告。

引用:

警告:传递“SDL_OpenAudioDevice”的参数 3 使指针来自整数而不进行强制转换

例如。

我尝试过的:

#include <stdio.h>
#include <stdlib.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_audio.h>

#define SAMPLE_RATE 44100
#define CHANNELS 1
#define BUFFER_SIZE 512

int main(int argc, char *argv[]) {
  // Initialize SDL.
  if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) {
    printf("SDL could not be initialized: %s\n", SDL_GetError());
    return 1;
  }

  // Create a window and renderer.
  SDL_Window *window = SDL_CreateWindow("Audio Spectrum", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN);
  SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

  // Create an audio device.
  SDL_AudioDeviceID device = SDL_OpenAudioDevice(NULL, 0, AUDIO_S16SYS, SAMPLE_RATE, BUFFER_SIZE);
  if (device == 0) {
    printf("Failed to open audio device: %s\n", SDL_GetError());
    return 1;
  }

  // Allocate memory for the audio buffer.
  short *buffer = malloc(BUFFER_SIZE * sizeof(short));

  // Create a texture to render the audio spectrum.
  SDL_Texture *texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGB24, SDL_TEXTUREACCESS_TARGET, 640, 480);

  // Main loop.
  while (1) {
    // Get the audio samples from the device.
    SDL_AudioStreamGet(device, buffer, BUFFER_SIZE);

    // Calculate the audio spectrum.
    int i, j;
    for (i = 0; i < BUFFER_SIZE; i++) {
      int sample = buffer[i];
      for (j = 0; j < SAMPLE_RATE/256; j++) {
        if (sample >= j * 256 / SAMPLE_RATE) {
          // Set the pixel at (i, j) to red.
          SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
          SDL_RenderDrawPoint(renderer, i, j);
        }
      }
    }

    // Render the audio spectrum.
    SDL_RenderClear(renderer);
    SDL_RenderCopy(renderer, texture, NULL, NULL);
    SDL_RenderPresent(renderer);

    // Sleep for a millisecond.
    SDL_Delay(10);
  }

  // Free resources.
  SDL_DestroyTexture(texture);
  SDL_Free(buffer);
  SDL_CloseAudioDevice(device);
  SDL_DestroyRenderer(renderer);
  SDL_DestroyWindow(window);
  SDL_Quit();

  return 0;
}

解决方案1

至少,您应该确定程序的哪一行出现了段错误。
使用调试器单步调试它,如果您知道它在哪一行执行此操作,您很可能能够说出原因。

此外,您确实应该了解为什么会收到这些警告,并采取适当的措施以确保没有警告。

[ad_2]

コメント

标题和URL已复制