我在 C 中有這個程式:
#include <stdio.h>
#include <string.h>
#include <stdint.h>
typedef struct sl{
int32_t length;
int32_t* arr;
} Selector;
void somefunction(Selector* temp){
temp->length = 10;
temp->arr = (int32_t*)malloc(temp->length * sizeof(int32_t));
for(int i=0; i<temp->length; i ){
temp->arr[i] = i*i;
}
}
int main () {
Selector* sel;
// Make changes to struct from other function
somefunction(sel);
// Print each element
for(int i=0; i<sel->length; i ){
printf("Content of index %d: %d\n",i,sel->arr[i]);
}
printf("\n");
return(0);
}
我使用 PowerShell 在 PowerShell 中運行它gcc .\stest.c; .\a.exe,它運行良好:
Content of index 0: 0
Content of index 1: 1
Content of index 2: 4
Content of index 3: 9
Content of index 4: 16
Content of index 5: 25
Content of index 6: 36
Content of index 7: 49
Content of index 8: 64
Content of index 9: 81
But if I change int main() to this:
int main () {
Selector* sel;
// Make changes to struct from other function
somefunction(sel);
// Print each element
for(int i=0; i<sel->length; i ){
printf("Content of index %d: %d\n",i,sel->arr[i]);
}
printf("\n");
// ============= ADDED CODE BELOW ============= //
// Change each element a bit
for(int i=0; i<sel->length; i ){
sel->arr[i] = sel->arr[i] 10;
}
// Print each element again
for(int i=0; i<sel->length; i ){
printf("Content of index %d after change: %d\n",i,sel->arr[i]);
}
printf("\n");
// ============= ADDED CODE ABOVE ============= //
return(0);
}
Suddenly it just gets a segmentation fault? Why? I didn't use the stack and overload it, I used malloc for the small arrays, it's not passing around references again like into the function to make memory go missing or something. Why doesn't this work? And how am I supposed to do it otherwise?
uj5u.com熱心網友回復:
歸功于給出解決方案的評論中的人。
該問題是由未定義的行為引起的,因為指標未設定為任何內容。
int main() {
Selector sel;
// Make changes to struct from other function
somefunction(&sel);
// Print each element
for(int i=0; i<sel.length; i ){
printf("Content of index %d: %d\n",i,sel.arr[i]);
}
printf("\n");
// ============= ADDED CODE BELOW ============= //
// Change each element a bit
for(int i=0; i<sel.length; i ){
sel.arr[i] = sel.arr[i] 10;
}
// Print each element again
for(int i=0; i<sel.length; i ){
printf("Content of index %d after change: %d\n",i,sel.arr[i]);
}
printf("\n");
// ============= ADDED CODE ABOVE ============= //
return(0);
}
總結一下,對于遇到同樣問題的后代和其他人:
- 不要讓“sel”成為指標。
- 發送“sel”作為參考。
- 相應地更改成員變數訪問。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/446158.html
標籤:c pointers struct segmentation-fault
下一篇:如何創建蒙版并在其上繪圖
