【问题标题】:c program works on windows take segmantation fault on linuxc程序在windows上工作在linux上出现分段错误
【发布时间】:2015-11-27 09:58:15
【问题描述】:

我在代码块上写了一些 c 代码。它在 Windows 上运行良好 但在 Linux 上给出了分段错误。为什么 ?

这是主要的。我使用了 3 个库和 opencells 方法调用递归方法。

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


int main(int argc , char *argv[])
{
     srand(time(NULL));
    int size=atoi(argv[1]),trial=atoi(argv[2]);      //! program basladıgında gelen argumanlar
    int i,j;                 //! dongu degişkenleri
        int **matrix = (int **)malloc(size * sizeof(int));          //!matriksin 1 boyutunu dinamik olarak yarattık
        int *counters = (int *)malloc(trial * sizeof(int));         //! buda counterları tutcagımız array

            for (i=0; i<size; i++)
                matrix[i] = (int *)malloc(size * sizeof(int)); //! 2. boyutada yarattık

         for(i=0;i<size;i++)
            for(j=0;j<size;j++)  //! matrixsi sıfırla saçma sapan degerler geliyo yoksa
                matrix[i][j]=0;

            for(i=0;i<trial;i++)
            {
                   counters[i]=opencells(matrix,size); //!Random kapı açan ve bunun sayısını donduren fonksyon
            }
            printboard(matrix,size,trial,counters); //!Output.txtye yazdır
            for (i=0; i<size; i++)
                free(matrix[i]);  //! ramden aldıgımız yerleri sal gitsin
            free(matrix);          //! bosu bosuna makinayı zorlamayalım
    return 0;
}

【问题讨论】:

  • 你知道你在哪里得到了段错误吗?
  • 创建核心转储,以便您可以查看导致段错误的命令。没有它,这是一个猜谜游戏
  • 不我在命令行上运行它 gcc -o main.c main 然后 ./main 10 100 它只是说 seg fault
  • 在计算 malloc 大小时不要使用“sizeof(int)”,而是正确执行。您为 matrix 分配了错误的大小。
  • @davidhood2:矩阵是用两层malloc创建的,所以它也应该在两层上被释放。每个malloc 都需要一个匹配的free

标签: c linux windows segmentation-fault


【解决方案1】:
int **matrix = (int **)malloc(size * sizeof(int));

更改:(int) 到 (int*)

int **matrix = (int **)malloc(size * sizeof(int*));

因为 sizeof(int) 和 sizeof(int*) 可能不同,所以你的程序在访问未分配的内存时可能会崩溃。

【讨论】:

  • 不要在 C 中转换 void *! C 不是 C++。而且您并没有真正解释 OP 做错了什么。
【解决方案2】:
int **matrix = (int **)malloc(size * sizeof(int)); 

更改:(int)(int*)

int **matrix = (int **)malloc(size * sizeof(int*));

在释放内存的同时使用

free(matrix[i]);
free(counters);

【讨论】:

    【解决方案3】:
    int **matrix = (int **)malloc(size * sizeof(int));
    

    您在此处分配了错误的内存量。你想要sizeof(int*),但你想要sizeof(int)

    在 Windows 上,int 和 int* 都是 32 位大的。在 linux 上,这可能会有所不同,从而导致您的程序在访问未分配的内存时出现分段错误。

    【讨论】:

      猜你喜欢
      • 2020-02-25
      • 1970-01-01
      • 2021-06-03
      • 2013-04-24
      • 1970-01-01
      • 2013-04-18
      • 1970-01-01
      • 2015-07-15
      • 2012-03-04
      相关资源
      最近更新 更多