为何读取文件的C代码在Visual Studio 2013报错却能在CodeBlocks正常运行?
Fixing the Debug Assertion Failed Error in Visual Studio 2013
Hey there! Let's break down why your code is throwing that "nptr!=NULL" assertion error in VS2013, even though it works in CodeBlocks.
The Root Cause
The issue lies in your while loop logic. Here's what's happening:
- When
strtokfinishes parsing all tokens in the line, it returnsNULL. - In your current code, you first call
p = strtok(NULL," ");(which setsptoNULLat the end) and then immediately passptoatoi(p). - Visual Studio's debug-mode C standard library is strict about invalid inputs—passing
NULLtoatoitriggers that assertion to warn you about the problem. CodeBlocks uses GCC/MinGW, which doesn't enforce this debug check by default, so you don't see the error there (but this is still undefined behavior that could cause crashes later!).
Fixed Code
Here's the corrected version of your code, with key improvements explained below:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { // Use standard int return type for main int v[30], i = 0; char line[30], *p; FILE *f = fopen("Text.txt","r"); // Always check if the file opened successfully if (f == NULL) { printf("Couldn't open the file!\n"); return 1; } // Only process if fgets successfully read a line if (fgets(line, 30, f) != NULL) { p = strtok(line, " "); // Loop correctly: check p before using it while (p != NULL) { v[i] = atoi(p); i++; p = strtok(NULL, " "); } } fclose(f); // Don't forget to close the file to free resources // Now i holds the exact number of elements we read for (int j = 0; j < i; j++) { printf("%d ", v[j]); } return 0; }
Key Changes Made
- Standard
mainfunction: Changedvoid maintoint main(void)—this is required by the C standard, as main should return an integer status code. - File open check: Added a check for
f == NULLto handle cases where the file can't be found or opened (e.g., if it's not in the correct directory for your VS project). - Fixed loop logic: Now we first check if
pis notNULLbefore callingatoi(p), then fetch the next token. This avoids passing aNULLpointer toatoi. - Closed the file: Added
fclose(f)to release the file handle, preventing resource leaks. - Corrected element count: The variable
inow directly represents the number of elements read, so we don't need to subtract 1 when settingn.
Why It Worked in CodeBlocks
GCC/MinGW (used by CodeBlocks) doesn't add the same debug assertions for function parameters that Visual Studio does. While your code ran without errors there, it was still doing something unsafe. The VS assertion is actually helpful—it's pointing out a bug that could cause unexpected behavior down the line.
内容的提问来源于stack exchange,提问作者Andreea Buzuriu
相关产品推荐
相关产品推荐

